1

On a site I am developing in Django, I want to restrict access to views so only superusers can access them. I could use @login_required or the LoginRequiredMixin, however I already have a login system for the average person, so that would let any logged in user access the view.

I've tried something that I thought would work SuperUserRequired as a mixin, however this obviously didn't work.

This has to be able to work in a CBV, as that's what I am using for this view. Here is the relevant view I want to apply this restriction to.

class CreatePostView(LoginRequiredMixin,CreateView):
    redirect_field_name = 'posts/post_detail.html'
    form_class = PostForm
    model = Post
    def form_valid(self,form):
        form.instance.author = self.request.user
        return super().form_valid(form)

Thanks for any help you can give :)

jeremy_lord
  • 469
  • 7
  • 23
  • You can add the user's role and add checks that the requested user role has access to this API or not. – Usman Maqbool Oct 03 '19 at 10:22
  • Why did `SuperUserRequired` mixin not work? Please show how you tried to use it. – Alasdair Oct 03 '19 at 10:45
  • 1
    You should consider using the [`PermissionRequiredMixin`](https://docs.djangoproject.com/en/2.2/topics/auth/default/#the-permissionrequiredmixin-mixin) with the `yourapp.add_post` permission. That way you can create regular users with just with that permission. Superusers will still be able to access the page, since they have all permissions. If you just check `user.is_superuser`, then it will be more difficult to have more granular restrictions later. – Alasdair Oct 03 '19 at 10:52

1 Answers1

6

I think you need this mixin described in docs. Basically it gives you opportunity to check whether user has right access rights or not. Below is modified code from docs also:

from django.contrib.auth.mixins import UserPassesTestMixin

class MyView(UserPassesTestMixin, View):
    def test_func(self):
        return self.request.user.is_superuser