about login_required

Where should I write “@login_required” in “class PostCreate(generic.CreateView):”

I got an error’PostCreate’ object has no attribute ‘user’ when I fill in above the “def get_context_data(self, **kwargs):”

Other pages display the login page normally.


from django.shortcuts import render, redirect
from datetime import datetime
from .forms import InquiryModelForm, PostModelForm, PostCreateForm
from .models import Repair_Case,  Post, ParentCategory
from .filters import InquiryFilter, PostFilter
from django.contrib.auth.decorators import login_required
from django.views import generic

def inquiry_Parts_Summary(request):
    form = Post.objects.all().order_by('-Data')
    myFilter = PostFilter(request.GET, queryset=form)
    form = myFilter.qs
    context = {
        'form': form, 'myFilter':myFilter,
    return render(request, 'App/inquiry_Parts_Summary.html', context)

def inquiry_detail(request, pk):
    inquiry = Repair_Case.objects.get(id=pk)
    context = {
        'inquiry': inquiry, 
    return render(request, 'AZApp/inquiry_detail.html', context)

class PostCreate(generic.CreateView):
    model = Post
    form_class = PostCreateForm
    success_url = 'inquiry-Parts_Summary'  

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['parentcategory_list'] = ParentCategory.objects.all()
        return context

Hey there!
In class-based-views you decorate the view on the url, check out the docs.

If you want to decorate the method, there’s a decorator for the login_required decorator :smile:. Also from the docs.

The above answer is good if you have a generic decorator you wish to apply. However, for the specific purpose of checking for a user being logged in, it’s probably better to use the LoginRequiredMixin. See Using the Django authentication system | Django documentation | Django

1 Like