An authentication system is included in Django in order to verify user credentials such as username, email and passwords.
The admin inteface is a default app installed by Django, and can be accessed at the /admin route.
A “superuser” is a special type of user object with permissions to manipulate other models.
python3 manage.py createsuperuser
Additional models can be registered in admin.py in order to be visible in the admin interface.
from django.contrib import adminfrom .models import ExampleModeladmin.site.register(ExampleModel)
The User
object can be used to perform various tasks such as restricting access, associating content, and registering user profiles.
user = User.objects.create_user(username="myusername", email="[email protected]", password="mypassword")
The authentication()
function is used to verify a user’s credentials against a database. It takes a request object, and two keyword arguments- the username
and password
.
from django.contrib.authuser = authenticate(request, username="erika1990", password="codec@demy!"")
If a user is authenticated, a view can use the login()
function to create a new session for the user.
from django.contrib.auth import authenticate, logindef signin(request):username = request.POST["username"]password = request.POST["password"]user = user.authenticate(request, username=username, password=password)if user is not None:login(request, user)else:...
The built-in login()
function uses a template in registration/login.html, which must be created. The template has access to the form fields through a form
instance wrapped in curly braces.
<form method="post"> {{ form.as_p }} </form>
A signup template can be created using the generic view CreateView
and the UserCreationForm
.
from django.contrib.auth.forms import UserCreationFormfrom django.urls import reverse_lazyclass SignUpView(CreateView):form_class = UserCreationFormsuccess_url = reverse_lazy("login")template_name = "registration/signup.html"
Page authorization can be enforced with decorators and mix-ins. The login_required
decorator is used for function-based views and the LoginRequiredMixin
for class-based views.
# Function Based View@login_requireddef private_page(request):# ...# Class Based Viewclass PrivatePage(LoginRequiredMixin, ListView):# ...
A user’s session can be ended using the built-in function, logout()
.
from django.contrib.auth import logoutdef logout_page(request):logout(request)