class AdminView(generic.ListView):
model = get_user_model()
fields = ['first_name', 'username', 'is_active']
template_name = 'users/admin.html'
class AdminUpdateView(UpdateView):
model = get_user_model()
fields = ['is_active']
template_name = 'users/user_update.html'
success_url = reverse_lazy('users:admin')
There are two views in django which I have created and I want them to be accessed only when the admin/staff logins. How do I go about it?
import asyncio from django. http import HttpResponse from django. views import View class AsyncView(View): async def get(self, request, *args, **kwargs): # Perform io-blocking view logic using await, sleep for example. await asyncio.
Django comes with a user authentication system. It handles user accounts, groups, permissions and cookie-based user sessions.
Generic class-based views are a great choice to perform all these tasks. It speeds up the development process. Django provides a set of views, mixins, and generic class-based views. Taking the advantage of it you can solve the most common tasks in web development.
from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...
You can use the UserPassesTestMixin
[Django-doc] and LoginRequiredMixin
[Django-doc] mixins, and specify as condition that the user should be an is_superuser
. Since you need these twice, we can make first a composite mixin:
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class AdminStaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin):
def test_func(self):
return self.request.user.is_superuser or self.request.user.is_staff
Next you can add the mixin to your class-based views:
class AdminView(AdminStaffRequiredMixin, generic.ListView):
model = get_user_model()
fields = ['first_name', 'username', 'is_active']
template_name = 'users/admin.html'
class AdminUpdateView(AdminStaffRequiredMixin, UpdateView):
model = get_user_model()
fields = ['is_active']
template_name = 'users/user_update.html'
success_url = reverse_lazy('users:admin')
You can use UserPassesTestMixin
:
from django.contrib.auth.mixins import UserPassesTestMixin
class AdminView(UserPassesTestMixin, generic.ListView):
model = get_user_model()
fields = ['first_name', 'username', 'is_active']
template_name = 'users/admin.html'
def test_func(self):
return self.request.user.is_staff or self.request.user.is_superuser
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With