Django is a high-level web framework that enables rapid development of secure, maintainable and scalable web applications. One of the most common tasks in web development is building forms that allow users to submit data to a web application. In this blog, we’ll cover how to build forms with Django.
Create a Django project
First, you’ll need to create a Django project. If you haven’t done this before, you can follow the official Django documentation to get started.
Create a Django app
Once you have a project, you can create a Django app. An app is a self-contained module that can be added to a Django project. You can create an app by running the following command:
manage.py startapp myapp
Replace “myapp” with the name of your app.
Define a form
Next, you’ll need to define a form. A form is a class that inherits from Django’s forms.Form class. In the form class, you define the fields that you want to include in the form. For example, here’s a simple form that includes a text field and a checkbox:
from django import forms
class MyForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
agree_to_terms = forms.BooleanField(required=True)
In this example, the name field is a required text field with a maximum length of 100 characters, the email field is a required email field, and the agree_to_terms field is a required checkbox.
Create a view
After defining the form, you’ll need to create a view that will render the form and process the data that the user submits. Here’s an example view that renders the form and processes the data:
from django.shortcuts import render
from .forms import MyForm
def my_view(request):
if request.method == ‘POST’:
form = MyForm(request.POST)
if form.is_valid():
# process the form data
name = form.cleaned_data[‘name’]
email = form.cleaned_data[’email’]
agree_to_terms = form.cleaned_data[‘agree_to_terms’]
# do something with the data
else:
form = MyForm()
return render(request, ‘my_template.html’, {‘form’: form})
In this example, the view checks the HTTP method of the request. If it’s a POST request, the view creates an instance of the form using the data that the user submitted. If the form is valid, the view processes the form data and does something with it (e.g., save it to a database). If the form is not valid, the view re-renders the form with error messages. If it’s a GET request, the view simply renders the form.
Create a template
Finally, you’ll need to create a template that renders the form. Here’s an example template that uses Django’s built-in form rendering capabilities:
<form method=”post”>
{% csrf_token %}
{{ form.as_p }}
<button type=”submit”>Submit</button>
</form>
In this example, the csrf_token template tag is used to include a CSRF token in the form (to protect against cross-site request forgery attacks), and the form.as_p template tag is used to render the form as a series of paragraphs (with each field wrapped in a <p> tag).
Handling file uploads
If you want to allow users to upload files, you can add a FileField or ImageField to your form class. To handle file uploads, you’ll need to set the enctype attribute of your form to “multipart/form-data” and use the request.FILES dictionary instead of request.POST in your view.
Customizing form rendering
Django provides a variety of built-in ways to render form fields, such as as_p, as_table, and as_ul, which can be used in your templates to generate different types of HTML markup for your form. If you want more control over how your form is rendered, you can also create custom form widgets or use third-party form rendering libraries like Crispy Forms.
Validating form data
Django provides a powerful form validation system that allows you to specify validation constraints for each form field, such as minimum and maximum values, regular expressions, and custom validation functions. If a form is submitted with invalid data, Django will automatically display error messages next to each field that failed validation.
Using ModelForms
If you’re building a form that’s closely related to a database model, you can use a ModelForm instead of a regular form. A ModelForm is a form that’s automatically generated based on a database model, which can save you a lot of time and effort when building forms that are tightly integrated with your database.
CSRF protection
As mentioned earlier, it’s important to include a CSRF token in your forms to protect against cross-site request forgery attacks. Django provides built-in CSRF protection, which you can enable by including the {% csrf_token %} template tag in your form templates and using the csrf_protect decorator or CsrfViewMiddleware middleware in your views.
Conclusion: That’s it! With these five steps, you can build forms with Django. Of course, there’s much more you can do with Django forms, such as custom validation, field rendering, and formsets, but this should be enough to get you started
If you’re looking to enhance your expertise in Django, LearnTube has got you covered with an array of online courses tailored to your needs. With the help of our specialized learning app and WhatsApp bot, you can enjoy a seamless learning experience. Our platform offers an extensive range of courses that cater to both novices and seasoned learners. For valuable insights, explore our diverse selection of courses on our website.