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 :)
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