3👍
✅
You can work with a UserPassesTestMixin
mixin [Django-doc]:
from django.contrib.auth.mixins import UserPassesTestMixin
class AddPostView(UserPassesTestMixin, CreateView):
# …
def test_func(self):
return self.request.user.is_superuser
# …
You can encapsulate this in a mixin:
from django.contrib.auth.mixins import UserPassesTestMixin
class AdminRequiredMixin(UserPassesTestMixin):
def test_func(self):
return self.request.user.is_superuser
and then use this mixin:
class AddPostView(AdminRequiredMixin, CreateView):
# …
def test_func(self):
return self.request.user.is_superuser
# …
Mixins should be put before the actual view in the inheritance hierarchy: otherwise these appear after the view in the method resolution order (MRO), and thus likely will not override the behavior (correctly).
2👍
class AddPostView(CreateView,LoginRequiredMixin):
model = Post
template_name = 'MainSite/add_post.html'
fields = '__all__'
def dispatch(self, request, *args, **kwargs):
if request.user.is_anonymous:
return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())
elif request.user.is_superuser:
return render(.....)
else
return super(AddPostView, self).dispatch(request, *args, **kwargs)
- [Django]-Django Uploaded images not displayed in production
- [Django]-Couldn't import Django error when I try to startapp
- [Django]-Django step through the code
- [Django]-What's the equivalent of Rails' Migrations or Django's South in Pylons and TG2?
- [Django]-How to send the javascript list of dictionaries object to django ajax
1👍
Use method_decorator and user_passes_test to achieve this
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test
class AddPostView(View):
@method_decorator(user_passes_test(lambda u: u.is_superuser))
def post(self, *args, **kwargs):
pass
- [Django]-How to send the javascript list of dictionaries object to django ajax
- [Django]-Django: how to set content-type header to text/xml within a class-based view?
- [Django]-How to show a django ModelForm field as uneditable
- [Django]-Django application deployed at suburl, redirect to home page after login
Source:stackexchange.com