Skip to content

Authentication#

Internal Auth Flow#

# urls.py
from django.contrib.auth import views as auth_views

urlpatterns = [
    path('login/', auth_views.LoginView.as_view(), name='login'),
    path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

Manual Login#

from django.contrib.auth import authenticate, login

user = authenticate(username=username, password=password)
if user is not None:
    login(request, user)

Check Authenticated (View)#

from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    return render(request, 'dashboard.html')

Check Authenticated (Template)#

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% else %}
    <a href="{% url 'login' %}">Login</a>
{% endif %}

Login Decorator (CBV)#

from django.contrib.auth.mixins import LoginRequiredMixin

class SecretView(LoginRequiredMixin, TemplateView):
    template_name = 'secret.html'

User Registration#

from django.contrib.auth.forms import UserCreationForm

def register(request):
    form = UserCreationForm(request.POST or None)
    if form.is_valid():
        form.save()
        return redirect('login')