0

I know I can check if a user is logged in using request.user.is_authenticated(), and I want to use a decorator for my class_based views, like the decorator for function views: login_required,what should I do?

I want something like this:

class AddCompanyInfoHandler(View):
    model = Company

    @check_login_decorator
       def get(self, request):
        form = EnrollCompanyForm()
        return render(request, 'student/company_form.html', {'form': form,})

    @check_login_decorator
        def post(self, request):
            form = EnrollCompanyForm(request.POST)
            if form.is_valid():
                form_data = form.cleaned_data
                current_user = request.user
                company = Company.objects.create_company(current_user, form_data)
                company.save()

                return HttpResponse("Create Company USer Successfully!")
            else:
                return render(request, 'student/company_form.html', {'form': form,})
Roger Liu
  • 1,768
  • 3
  • 16
  • 25
  • FYI, http://stackoverflow.com/questions/6069070/how-to-use-permission-required-decorators-on-django-class-based-views. – alecxe May 07 '13 at 04:01

2 Answers2

2

This my bring some light.

In short, you have to decorate the dispatch method of the class and every instance of that class will be protected by the login_decorator. In your case should be like this:

from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

class AddCompanyInfoHandler(View):

    ...

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(AddCompanyInfoHandler, self).dispatch(*args, **kwargs)

Note: There's also nice info in this question.

Hope it helps!

Community
  • 1
  • 1
Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
0

You have to assign the login required to the whole class.

@login_required
class AddCompanyInfoHandler(View):
    ...

And be careful about the indentation,(with reference to the functions in your class)

If you are using bare functions for views instead of classes, the decorator goes like this

@login_required
def home(request):
    if request.method=='GET':
        ...
    else:
        ...
rjv
  • 6,058
  • 5
  • 27
  • 49