![]() |
VOOZH | about |
Handling HTML forms is a fundamental part of web development. In Django, forms allow users to submit data to the server for processing, whether saving it to a database or retrieving information, while leveraging Django’s built-in form handling capabilities.
An HTML form is a collection of input elements wrapped inside <form>...</form> tags. Forms let users:
The server then handles this data, often involving database operations or custom logic. Django fully supports HTML forms and simplifies both rendering and processing of form data using views.
Example url:
https://docs.djangoproject.com/en/5.2/search/?q=forms
Consider a project named 'geeksforgeeks' having an app named 'geeks'.
Create home.html in geeks/templates/:
This form will send data using the GET method when submitted.
In geeks/urls.py:
In geeks/views.py:
python manage.py runserver
Submitting the form will append data to the URL, which can be accessed in the view using request.GET.
After entering a name and submitting the form, the data will be printed in the terminal:
request.GET returns a QueryDict object. While it behaves similarly to a Python dictionary, it is specifically designed to handle multiple values for the same key. For example, to retrieve a single value, you use .get(), but to retrieve a list of multiple values for one key, you must use the .getlist() method.
To use POST instead of GET, modify form in home.html:
Django requires the {% csrf_token %} template tag inside all POST forms for security to prevent Cross-Site Request Forgery attacks.
Modify view to handle POST data:
Submit the form it shows the data:
This way one can use this data for querying into the database or for processing using some logical operation and pass using the context dictionary to the template.
| HTML Forms | Django Forms |
|---|---|
Standard forms written in HTML using <form> tags. | Abstracted forms defined as Python classes in Django. |
| Data handling and validation must be manually implemented in the view. | Provides built-in data validation, rendering, and handling. |
| No direct integration with Django models. | Can be linked directly to Django models using ModelForm. |
| Suitable for simple forms or quick prototypes. | Ideal for robust, secure, and reusable form handling. |
| Form fields are defined in HTML with attributes like type, name, and required. | Form fields are defined in Python using Django’s forms module. |