Render Django Forms
Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). A form comes with 3 in-built methods that can be used to render Django form fields.
- {{ form.as_table }} will render them as table cells wrapped in <tr> tags
- {{ form.as_p }} will render them wrapped in <p> tags
- {{ form.as_ul }} will render them wrapped in <li> tags
To render this form into a view, move to views.py and create a home_view as below.
from django.shortcuts import render
from .forms import InputForm
# Create your views here.
def home_view(request):
context ={}
context['form']= InputForm()
return render(request, "home.html", context)
In view, one needs to just create an instance of the form class created above in forms.py. Now let’s edit templates > home.html
<form action = "" method = "post">
{% csrf_token %}
{{form }}
<input type="submit" value=Submit">
</form>
Now, visit http://localhost:8000/
.
To check how to use the data rendered by Django Forms visit Render Django Form Fields
Django Forms
When one creates a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. This article revolves around various fields one can use in a form along with various features and techniques concerned with Django Forms.