Darshan Chaudhary
Darshan Chaudhary

Reputation: 2233

django - authenticate users using django.test.Client

In my tests, I am trying to create and authenticate a User but when I hit my views, it still returns 302

def test_Home(self):
    self.client = Client()
    self.user = User.objects.create_user("xoxo", password="bar", is_staff=True)
    self.logged_in = self.client.login(
        username="xoxo", password="bar")
    r = self.client.get('/hudson/')
    self.assertEqual(r.status_code, HTTP_200_OK)

My /hudson/ view is simply:

class HomeView(PermissionRequiredMixin, generic.TemplateView):
    template_name = 'foo/base.html'
    permission_required = ('user.is_staff', )
    login_url = reverse_lazy('admin:login')

I am getting 302 to my admin/login as define in the view.

Upvotes: 1

Views: 205

Answers (1)

Alasdair
Alasdair

Reputation: 308999

is_staff is an attribute on the user instance, not a permission. You are redirected because the user does not have a permission 'user.is_staff'.

You could use the UserPassesTestMixin mixin instead:

from django.contrib.auth.mixins import UserPassesTestMixin

class HomeView(UserPassesTestMixin, generic.TemplateView):
    def test_func(self):
        return self.request.user.is_staff 

    template_name = 'foo/base.html'
    login_url = reverse_lazy('admin:login')

If you do this in multiple views, you can create your own mixin.

class UserIsStaffMixin(UserPassesTestMixin):
    def test_func(self):
        return self.request.user.is_staff 

    login_url = reverse_lazy('admin:login')

class HomeView(UserIsStaffMixin, generic.TemplateView):
    template_name = 'foo/base.html'

Upvotes: 3

Related Questions