form design bootstrap
forms.py
from django import forms
from .models import Student
class ReusableForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'email', 'date_of_birth']
def __init__(self, *args, **kwargs):
super(ReusableForm, self).__init__(*args, **kwargs)
for field_name, field in self.fields.items():
field.widget.attrs.update({
'class': 'form-control',
'id': f"defaultForm-{field_name}",
})
# no need this
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'email', 'date_of_birth']
views.py
def student_create(request):
if request.method == 'POST':
form = ReusableForm(request.POST)
if form.is_valid():
form.save()
return redirect('student_list')
else:
form = ReusableForm()
return render(request, 'students/student_form.html', {'form': form})
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 5 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container-fluid p-5 bg-primary text-white text-center">
<h1>My First Bootstrap Page</h1>
<p>Resize this responsive page to see the effect!</p>
</div>
<div class="container mt-5">
<div class="row">
{% block content %}
{% endblock %}
</div>
</div>
</body>
</html>
student_form.html
{% extends 'base.html' %}
{% block content %}
<!-- এখানে কনটেন্ট পরিবর্তনের কোড থাকবে -->
<h1>{% if form.instance.id %}Edit{% else %}Add{% endif %} Student</h1>
<form method="post">
{% csrf_token %}
{% for field in form %}
<div class="col-md-4 mb-4">
<div class="form-group">
<label for="{{ field.auto_id }}">{{ field.label }}</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fas fa-envelope"></i>
</span>
</div>
{{ field }}
</div>
</div>
</div>
{% endfor %}
<button type="submit">Save</button>
</form>
<a href="{% url 'student_list' %}">Back to list</a>
{% endblock %}
<!-- students/student_form.html -->
Last updated