2
votes

I am using Django Generic view, DetailView. But I'd like to block users to access to detail post who did not email_confirmed yet. I have a email_confirmed field in User model.

My code is :

@method_decorator(login_required(login_url='/login/'), name='dispatch')
class RecruitView(generic.DetailView):
    model = Recruit
    template_name = 'recruit.html'

and I want to add :

    if not request.user.email_confirmed:
        error_message = "you did not confirmed yet. please check your email."
        return render(request, 'info.html', {'error_message': error_message})
    else: pass

How can I add this condition to DetailView?

(I tried to override 'as_view' but I don't know how to do it)

1

1 Answers

7
votes

I would use the PermissionRequiredMixin. With this you can specify specific permissions users need to have or override the has_permission method.

from django.contrib.auth.mixins import PermissionRequiredMixin

class RecruitView(PermissionRequiredMixin, generic.DetailView):
    ...

    login_url = '/login/'
    permission_denied_message = 'you did not confirmed yet. please check your email.'

    def has_permission(self):
         return self.request.user.email_confirmed

This will redirect users without the email_confirmed to the login_url where you can display the error message. In order to use the index.html template instead you might need to override the handle_no_permission method.