Codecademy Logo

Accounts and Authentication

Authentication

An authentication system is included in Django in order to verify user credentials such as username, email and passwords.

Admin Interface

The admin inteface is a default app installed by Django, and can be accessed at the /admin route.

superuser

A “superuser” is a special type of user object with permissions to manipulate other models.

python3 manage.py createsuperuser

Registering Database Table

Additional models can be registered in admin.py in order to be visible in the admin interface.

from django.contrib import admin
from .models import ExampleModel
admin.site.register(ExampleModel)

User Objects

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")

Authenticating Users

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.auth
user = authenticate(request, username="erika1990", password="codec@demy!"")

Logging In

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, login
def 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:
...

Login Template

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>

Sign Up Template

A signup template can be created using the generic view CreateView and the UserCreationForm.

from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
class SignUpView(CreateView):
form_class = UserCreationForm
success_url = reverse_lazy("login")
template_name = "registration/signup.html"

Login Mixin and Decorator

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_required
def private_page(request):
# ...
# Class Based View
class PrivatePage(LoginRequiredMixin, ListView):
# ...

Logging Out

A user’s session can be ended using the built-in function, logout().

from django.contrib.auth import logout
def logout_page(request):
logout(request)

Learn more on Codecademy