Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a django view, how do I redirect a user to the login view if that don't belong to the object set?

I feel like this is really simple and I'm just missing it.

I have a very simple generic class based view detail.

When I do teh get_object I want to make sure that the request.user is in the set that belongs to the object. If not, redirect them to the login.

Here's my view:

class AwesomeDetail(LoginRequiredMixin, DetailView):
    """
    An awesome detail
    """
    template_name = "awesomeness/detail.html"

    def get_object(self):
        awesomeness = ModelName.objects.get(id=self.kwargs['pk'])
        if self.request.user in awesomeness.staff.all():
            return awesomness
        else:
            return redirect('account_login')

Staff is a many to many to users. What am I missing? The redirect isn't happening. It renders the template, but of course, awesomeness is missing.

like image 980
Dave Merwin Avatar asked Nov 15 '25 06:11

Dave Merwin


2 Answers

UserPassesTestMixin was introduced in Django 1.9.

You define a test_func method to return True/Fales depending on whether the test passes.

If the user fails the test they will be redirected to settings.LOGIN_URL with a redirect field.

UserPassesTestMixin supports any of the fields for AccessMixin.

from django.contrib.auth.mixins import UserPassesTestMixin


class AwesomeDetail(UserPassesTestMixin, LoginRequiredMixin, DetailView):
    """
    An awesome detail
    """
    template_name = "awesomeness/detail.html"
    model = ModelName

    def test_func(self):
        if self.request.user in self.object.staff.all():
            return True
        else:
            return False
like image 69
James Fenwick Avatar answered Nov 17 '25 20:11

James Fenwick


I'm not very sure about this, but sounds like get method is the one you should work on:

class AwesomeDetail(LoginRequiredMixin, DetailView):
    """
    An awesome detail
    """
    template_name = "awesomeness/detail.html"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        if not self.request.user in self.object.staff.all():
            return redirect('account_login')
        else:
            return super(AwesomeDetail, self).get(request, *args, **kwargs)
like image 27
Shang Wang Avatar answered Nov 17 '25 22:11

Shang Wang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!