Why LoginRequiredMixin don't stop my dispatch flow, when user is not authenticated

76 Views Asked by At

I have no clue why in this View, dispatch does not end after super():

class CreateBookView(LoginRequiredMixin, CreateView):
template_name = 'library/create_book.html'
form_class = BookForm

def dispatch(self, request, *args, **kwargs):
    result = super().dispatch(request, *args, **kwargs)
    if self.request.user.is_authenticated and not self.request.user.contactform.is_completed:
        return redirect(reverse_lazy('edit_contacts') + f"?next={self.request.path}#edit")
    return result

def form_valid(self, form):
    form.instance.owner = self.request.user
    form.instance.category = self._set_category(form)
    return super().form_valid(form)

def get_success_url(self):
    pk = self.request.user.pk
    default_redirect = reverse_lazy('show_books_dashboard', kwargs={'pk': pk})
    next_page = self.request.GET.get('next')
    return next_page if next_page else default_redirect

@staticmethod
def _set_category(form):
    category = form.cleaned_data.get('category')
    category_name = form.cleaned_data.get('category_name')
    if category or not category_name:
        return category
    new_category, created = Category.objects.get_or_create(name=category_name)
    return new_category

But in this it works as I expected and end it:

class DetailsNotificationView(LoginRequiredMixin, AuthorizationRequiredMixin, DetailView):
    model = Notification
    context_object_name = 'notification'
    template_name = 'common/notifications/notifications_details.html'
    authorizing_fields = ['recipient']

    def dispatch(self, request, *args, **kwargs):
        result = super().dispatch(request, *args, **kwargs)
        notification = self.get_object()
        notification.is_read = True
        notification.save()
        if notification.offer:
            return redirect('show_offer_details', pk=notification.offer.pk)
        return result

I expect LoginRequiredMixin to handle error immediately after super() when the user is not authenticated and stop dispatch flow. I cannot figure out why it does not work as expected in CreateBookView. Any ideas ?

0

There are 0 best solutions below