Django forms and user registration
In the previous lesson we learned how Django uses models and the database.
Now we will see how users can enter data through web forms.
What is a Django form?
A form is an HTML element that lets users enter data on a web page.
An example of a simple HTML form:
<form method="post">
<input type="text" name="name">
<button type="submit">Send</button>
</form>
The Django forms system
Django has a special system for working with forms that makes validating data easier.
A form is defined in the file forms.py.
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
message = forms.CharField(widget=forms.Textarea)
Displaying the form in a template
The form is displayed in an HTML template.
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
Django uses CSRF protection to prevent attacks on the application.
Processing the form in a view function
from django.shortcuts import render
from .forms import ContactForm
def contact(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
name = form.cleaned_data["name"]
else:
form = ContactForm()
return render(request, "contact.html", {"form": form})
User registration
Django already has a built-in user authentication system.
This means we can easily make:
- user registration
- a login system
- logout
- profile management
An example of user registration
from django.contrib.auth.models import User
user = User.objects.create_user(
username="mark",
password="secret123"
)
This code creates a new user in the database.
The Django login page
Django makes it easy to add a login system to an application.
from django.contrib.auth import authenticate, login
Related tutorials
If you want to see how a complete Django application works in practice, see the following tutorials:
Frequently asked questions
What is a Django form?
A Django form lets you enter and validate data.
What is a CSRF token?
A CSRF token protects the application from unauthorized requests.
Does Django have a system for users?
Yes. Django has a built-in system for authentication and user management.
Can we make a login system?
Yes. Django makes it easy to build login and registration pages.
