Defining Forms
Django provides some facilities for generating and validating forms, which relieve you of the task of manually writing the HTML code and the Python code responsible for verifying that the data entered is valid.
We have at http://127.0.0.1:8000/myapp/courses a view that lists courses stored in the database. Now we will implement a form to insert courses. First, create a file called myapp/forms.py
with the following code:
from django import forms
class CourseForm(forms.Form):
name = forms.CharField(label="Name", max_length=128)
enrolled_students = forms.IntegerField(label="Students")
We are defining a form named CourseForm
with two fields: name
, of type forms.CharField
(that is, a one-line text) with a maximum of 128 characters (it is always a good practice to define some maximum value), and enrolled_students
, of type forms.IntegerField
. The label
argument in each of them indicates the title that will appear next to the field when rendering the form.
Depending on the type chosen for each of the fields, Django will apply different validations. For example, for fields defined as forms.IntegerField
, it will ensure that the text entered can be converted to an integer.
Secondly, in views.py
, import this form at the beginning of the file and define a new view in which an instance of the form is created.
Forms are defined in the forms.py
file, while functions in views.py
create instances of them. The same form definition can be used to create multiple instances in different views. In other words, you can use the same form in different pages.
from . import forms
# ...
def new_course(request: HttpRequest) -> HttpResponse:
form = forms.CourseForm()
ctx = {"form": form}
return render(request, "myapp/new_course.html", ctx)
We are creating an instance of the form defined in forms.py
, adding it to the context and passing it to the myapp/new_course.html
. Now create the templates/myapp/new_course.html
template with the following content content:
<h1>New course</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Add course">
</form>
Let's explain this:
<form method="post">
is the regular HTML code for creating a form. Remember that forms use the HTTPPOST
method when sending the request to the server. We will see immediately how this affects our Django code.{% csrf_token %}
is a variable that Django automatically adds to the context of our template and that generates code that protects the form from certain vulnerabilities (see https://en.wikipedia.org/wiki/Cross-site_request_forgery.) For this reason you will always include it in templates used to display forms.{{ form.as_p }}
renders the HTML code for the fields that defined informs.CourseForm
. You can also just use{{ form }}
to generate the form on the same line. Theas_p
addition indicates that<p>
tags should be used for each field, which will display one field per line.
Finally, bind the newly created view with a URL pattern in myapp/urls.py
:
urlpatterns = [
path("", views.index, name="index"),
path("about-us", views.about_us, name="about_us"),
path("courses", views.courses, name="courses"),
path("courses/json", views.courses_json, name="courses_json"),
path("course/<str:course_name>", views.course, name="course"),
path("new-course", views.new_course, name="new_course")
]
Visit http://127.0.0.1:8000/myapp/new-course and you will see:
Perfect! These are the steps to define and render a form in Django. In the next section, you will learn how to validate and process a form.