Write Django Forms
Why Django Forms
Handling forms is a complex business. Consider Django’s admin, where numerous items of data of several different types may need to be prepared for display in a form, rendered as HTML, edited using a convenient interface, returned to the server, validated and cleaned up, and then saved or passed on for further processing.
Introduction to Django Forms
Django forms provide a way to handle user input in a Django web application. Forms can be used to validate user input, sanitize data, and save data to a database.
Form Class
In Django, a form is a Python class that inherits from the django.forms.Form class or one of its subclasses. A form is defined by specifying the fields it contains, as well as any validation or cleaning logic. When a form is submitted, the data entered by the user is passed to the form, and the form performs any validation or cleaning required. If the data is valid, it can be processed further or saved to a database.
Django Form Fields
Django provides several built-in form fields, such as CharField, IntegerField, EmailField, and BooleanField, among others. You can also define custom form fields if you need to handle data in a specific way.
Django Form Rendering in HTML
Django forms can be rendered as HTML forms using the as_p, as_table, or as_ul methods, which generate HTML code that can be included in a web page. You can also customize the appearance of forms by using CSS or by rendering the form fields manually.
Django Multimedia Form Handeling
Django also provides support for handling file uploads through forms, using the FileField and ImageField form fields. When a file is uploaded, Django handles the file data and saves it to a specified location on the server.
Write Django Forms
I guess above intro is enough to understand its functionality and need. Lets write first Django Form for user signup.
Django forms must be in forms.py file which should be in app root directory.
Add following on the top of forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Blog, Comment
SignUp Form
Since we use Django's built-in User model, we don't build a signup form from scratch. Django ships UserCreationForm, which already knows how to validate a username, ask for the password twice, and store it as a secure hash. We only extend it to also collect an email address. Let's have a look into the code.
class SignUpForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
# ...
In above code, Meta is a subclass of the SignUpForm class and is used to provide metadata to the SignUpForm class.
Specifically, Meta is used to define the model class (User) and the fields that should be included in the form. password1 and password2 are the two password fields UserCreationForm provides — it checks that both entries match and runs Django's password validators before saving. When the form is rendered, it will include HTML input elements for each of these fields.
The Meta subclass can also be used to provide additional information about the form, such as custom validation logic, field ordering, or help text for individual fields.
Login Form
The login form is not a ModelForm — it doesn't create or update any row in the database. It only collects a username and password that the view passes to authenticate(). A plain forms.Form is the right tool here. Let's have a look into the code.
class LoginForm(forms.Form):
username = forms.CharField(max_length=150)
password = forms.CharField(widget=forms.PasswordInput)
widget=forms.PasswordInput renders the field as a password input, so the browser masks it while typing.
Blog Form
Blog form will be related to Blog model. The author field is not part of the form on purpose — the view fills it from request.user. Let's have a look into the code.
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = ['title', 'content', 'image']
Comment Form
Comment form will be related to Comment model. The user only types the comment text — the view fills in blog and author itself. Let's have a look into the code.
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['comment']
Final File
After writing above code, forms.py should look like following
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Blog, Comment
class SignUpForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class LoginForm(forms.Form):
username = forms.CharField(max_length=150)
password = forms.CharField(widget=forms.PasswordInput)
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = ['title', 'content', 'image']
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['comment']