</>
Skip to content
Django lessons (22/43)

Django — Authentication

Built-in Auth

Django provides built-in authentication views:

# 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'),
    path('password-change/', auth_views.PasswordChangeView.as_view(), name='password_change'),
]

Settings

# settings.py
LOGIN_URL = '/login/'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

Login Template

<!-- templates/registration/login.html -->
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Login</button>
</form>

Custom Registration

# accounts/forms.py
class RegistrationForm(forms.Form):
    username = forms.CharField(max_length=50)
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)
    
    def save(self):
        user = User.objects.create_user(
            username=self.cleaned_data['username'],
            email=self.cleaned_data['email'],
            password=self.cleaned_data['password']
        )
        return user

Protecting Views

from django.contrib.auth.decorators import login_required

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

Mini Practice

  1. Set up login/logout URLs
  2. Create registration form
  3. Use @login_required decorator
  4. Customize auth templates

Up Next

Continue with User Management — managing user profiles.

Related Topics

Frequently Asked Questions about Authentication

What is Authentication in Django?

Authentication is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Authentication?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Authentication.

Why is Authentication important in Django?

Authentication is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.