Django Tutorial
Django Create A Complete Project
Django Template
Django Database Query
Django Form
Django Authentication and Permission Management
Django unittest
Django Advanced
Django is a powerful and versatile web framework for Python that makes it easy to create web applications quickly. One of its key features is the ability to handle and process forms. Django's Form API provides a convenient way to create, render, and validate form data.
In this tutorial, we'll cover:
Before we dive in, make sure you have Django installed on your system. If not, install it using pip:
pip install django
First, let's create a basic Django Form. In your Django app, create a file named forms.py
and add the following code:
from django import forms class ContactForm(forms.Form): name = forms.CharField(label="Name", max_length=100) email = forms.EmailField(label="Email") message = forms.CharField(label="Message", widget=forms.Textarea)
This code creates a simple ContactForm
with three fields: name, email, and message. We've used Django's built-in form fields (e.g., CharField
, EmailField
) and widgets (e.g., Textarea
) to define these fields.
Next, let's create a template to render the form. In your app's templates
folder, create a file named contact.html
and add the following code:
{% for field in form %} <div class="form-group"> <label for="{{ field.auto_id }}">{{ field.label }}</label> {{ field }} </div> {% endfor %}
This code iterates through the form fields and renders them with their respective labels.
Now, let's create a view to handle the form submission and validation. In your app's views.py
file, add the following code:
from django.shortcuts import render from .forms import ContactForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): # Process the data in form.cleaned_data # ... return render(request, 'success.html') else: form = ContactForm() return render(request, 'contact.html', {'form': form})
This view creates a new instance of ContactForm
and populates it with the submitted data if the request method is POST. It then checks if the form is valid by calling form.is_valid()
. If the form is valid, you can process the data in form.cleaned_data
. Otherwise, a new empty form is created.
Finally, add the corresponding URL pattern for the view in your app's urls.py
file:
from django.urls import path from . import views urlpatterns = [ path('contact/', views.contact, name='contact'), ]
Django allows you to customize form rendering, which can help you achieve the desired look and feel for your form. For example, you can add Bootstrap classes to your form fields:
from django import forms class ContactForm(forms.Form): name = forms.CharField(label="Name", max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) email = forms.EmailField(label="Email", widget=forms.EmailInput(attrs={'class': 'form-control'})) message = forms.CharField(label="Message", widget=forms.Textarea(attrs={'class': 'form-control'}))
Creating forms in Django using Form API:
# forms.py in your app from django import forms class MyForm(forms.Form): name = forms.CharField(label='Your Name', max_length=100) email = forms.EmailField(label='Your Email') message = forms.CharField(label='Your Message', widget=forms.Textarea)
Django form validation and handling:
# forms.py in your app from django import forms class MyForm(forms.Form): # ... (fields definition) def clean_name(self): name = self.cleaned_data['name'] if len(name) < 3: raise forms.ValidationError('Name must be at least 3 characters long.') return name
Django form widgets and fields:
# forms.py in your app from django import forms class MyForm(forms.Form): date_of_birth = forms.DateField(widget=forms.SelectDateWidget)
Form handling in Django views:
# views.py in your app 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 valid form data else: form = MyForm() return render(request, 'my_template.html', {'form': form})
Django ModelForm API usage:
# forms.py in your app from django import forms from .models import MyModel class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['name', 'email', 'message']
Django form templates and rendering:
<!-- my_template.html --> <form method="post" action="{% url 'my_view' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form>
Django form handling in class-based views:
# views.py in your app from django.views import View from django.shortcuts import render from .forms import MyForm class MyFormView(View): template_name = 'my_template.html' def get(self, request): form = MyForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = MyForm(request.POST) if form.is_valid(): # Process valid form data return render(request, self.template_name, {'form': form})