Interview question
How do you render Django forms in templates, and what are the different rendering options? Django templates में forms कैसे render करें, और अलग-अलग rendering options क्या हैं?
Answer
| Rendering method | Control level | Use case |
|---|---|---|
| {{ form }} | Least control | Quick prototyping |
| {{ form.as_p }} / as_table / as_ul | Basic layout choice | Simple, standard layouts |
| Manual field-by-field | Full control | Custom design, specific styling |
<!-- Quick rendering options -->
<form method='post'>
{% csrf_token %}
{{ form.as_p }} <!-- each field wrapped in <p> tags -->
<button type='submit'>Submit</button>
</form>
<!-- Alternatives: {{ form.as_table }}, {{ form.as_ul }} -->
<!-- Manual field-by-field rendering - full control over markup -->
<form method='post'>
{% csrf_token %}
<div class='form-group'>
<label for='{{ form.title.id_for_label }}'>Title</label>
{{ form.title }}
{% if form.title.errors %}
<div class='error'>{{ form.title.errors }}</div>
{% endif %}
{% if form.title.help_text %}
<small>{{ form.title.help_text }}</small>
{% endif %}
</div>
<div class='form-group'>
<label for='{{ form.price.id_for_label }}'>Price</label>
{{ form.price }}
{{ form.price.errors }}
</div>
<button type='submit'>Submit</button>
</form>
<!-- Looping over all fields for consistent custom rendering -->
<form method='post'>
{% csrf_token %}
{% for field in form %}
<div class='form-group'>
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
</div>
{% endfor %}
<button type='submit'>Submit</button>
</form>
<!-- Non-field errors (from the form's clean() method) -->
{{ form.non_field_errors }}
<!-- Customizing widget attributes in Python (e.g. for CSS classes) -->
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'price']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
}| Rendering method | Control | Use case |
|---|---|---|
| {{ form }} | सबसे कम | Quick prototyping |
| as_p / as_table / as_ul | Basic layout | Simple layouts |
| Manual field-by-field | पूरा control | Custom design |
<form method='post'>
{% csrf_token %}
{{ form.as_p }}
<button type='submit'>Submit</button>
</form>
<!-- Manual field-by-field -->
<form method='post'>
{% csrf_token %}
<div class='form-group'>
<label for='{{ form.title.id_for_label }}'>Title</label>
{{ form.title }}
{% if form.title.errors %}
<div class='error'>{{ form.title.errors }}</div>
{% endif %}
</div>
<button type='submit'>Submit</button>
</form>
<!-- सभी fields loop करना -->
<form method='post'>
{% csrf_token %}
{% for field in form %}
<div class='form-group'>
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
</div>
{% endfor %}
<button type='submit'>Submit</button>
</form>
{{ form.non_field_errors }}
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'price']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
}Was this answer clear?