What are Forms?
Forms are essential components of web applications that allow users to input data. Whether it's a registration form, a search bar, or a feedback form, Django provides a robust way to handle user input effortlessly. In this blog post, you will learn step by step process to create a form in Django.
Step 1: Define a Form Class
Open the file of your Django app where you want to create the form.
Import the necessary modules:
from django import forms
Define a form class by creating a subclass of
forms.Form
orforms.ModelForm
(if you have to create a form from model attributes)class MyForm(forms.Form): name = forms.CharField(label='Name') email = forms.EmailField(label='Email') age = forms.IntegerField(label='Age')
Step 2: Create a Template for the Form
Inside your app's templates directory, create a new HTML template file (e.g.,
form_template.html
).Open the template file and add the following code to render the form:
<form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> </form>
Step 3: Process the Form Data in a View
Open the file containing your Django views (e.g.,
views.py
).Import the necessary modules:
from django.shortcuts import render
Create a view function that handles the form submission and processes the data:
def process_form(request): if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] age = form.cleaned_data['age'] # Process the form data else: form = MyForm() return render(request, 'form_template.html', {'form': form})
Step 4: Connect the URLs
Open the file containing your app's URLs (e.g.,
urls.py
).Import the views module:
from . import views
Add a URL pattern to map the form view to a specific URL:
urlpatterns = [ # other urls path('form/', views.process_form, name='process_form'), ]
Step 5: Test Your Form
Start the Django development server, if not already running.
Open a web browser and navigate to the URL corresponding to the form view you defined (e.g.,
http://localhost:8000/form/
).Fill in the form fields and submit the form.
Verify that the form data is processed correctly and any desired actions are performed.
Congratulations! You have successfully created a form in Django and implemented the necessary steps to handle form data. Feel free to customize the form class, template, and view to suit your specific requirements.
refer to Django's documentation for more in-depth explanations from the below links.
Links to refer to: