How to Secure Django Views with LoginRequiredMixin

3D isometric illustration of a bouncer checking IDs at a VIP entrance, representing the Django LoginRequiredMixin.

You’ve built a full CRUD application and a Login System. But there’s a huge security hole: Anyone can visit /post/5/edit/ and change your posts! To solve this, you need to use Django LoginRequiredMixin in your views to restrict access only to authenticated users.

We need to “lock” those pages so only logged-in users can access them.

Method 1: For Function-Based Views (@login_required)

If you wrote a simple function view, you use a decorator.

from django.contrib.auth.decorators import login_required

@login_required
def my_secret_view(request):
    # This code will ONLY run if the user is logged in.
    # If they are not, Django will automatically redirect them
    # to the login page.
    return render(request, 'secret_page.html')

Method 2: For Class-Based Views (LoginRequiredMixin)

This is the modern way to protect your generic views (ListView, UpdateView, etc.). You just add the LoginRequiredMixin to the class definition.

Important: The Mixin must come before the main View.

pages/views.py

from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from .models import Post

# This view is still public for everyone
class PostListView(generic.ListView):
    model = Post
    template_name = 'pages/post_list.html'

# This view is now PROTECTED
class PostUpdateView(LoginRequiredMixin, generic.UpdateView):
    model = Post
    fields = ['title', 'text']
    template_name = 'pages/post_edit.html'
    login_url = '/accounts/login/' # (Optional: where to send them)

# This view is also PROTECTED
class PostDeleteView(LoginRequiredMixin, generic.DeleteView):
    model = Post
    template_name = 'pages/post_delete.html'
    success_url = reverse_lazy('post_list')

That’s it! By adding LoginRequiredMixin, you’ve secured your edit and delete pages from the public.

Key Takeaways

  • Securing your CRUD application is crucial as anyone can edit posts without login.
  • For function-based views, use the @login_required decorator to restrict access.
  • For class-based views, implement LoginRequiredMixin to protect your generic views.
  • Always place the Mixin before the main View in your class definition.
  • Using LoginRequiredMixin effectively locks your edit and delete pages from public access.

Similar Posts

Leave a Reply