Django groups and permissions

2024/10/5 3:18:39

I would like to create 2 groups (Professors, Students). And I would like to restrict students from creating and deleting Courses.

views.py:

def is_professor(function=None):def _is_professor(u):if user.groups.filter(name='Professor').exists():return Trueelse:raise HttpResponseForbiddenreturn _is_professor(function)class ListCourseView(ListView):model = Coursetemplate_name = 'course_list.html'fields = '__all__'@is_professor
class CreateCourseView(CreateView):def get_queryset(self, request):if not request.user.is_superuser:return Falsemodel = Coursetemplate_name = 'course/edit_course.html'fields = '__all__'def get_success_url(self):return reverse('courses-list')def get_context_data(self, **kwargs):context = super(CreateCourseView, self).get_context_data(**kwargs)context['action'] = reverse('courses-new')return contextclass UpdateCourseView(UpdateView):model = Coursetemplate_name = 'course/edit_course.html'fields = '__all__'def get_success_url(self):return reverse('courses-list')def get_context_data(self, **kwargs):context = super(UpdateCourseView, self).get_context_data(**kwargs)context['action'] = reverse('courses-edit',kwargs={'pk': self.get_object().id})return contextclass DeleteCourseView(DeleteView):model = Coursetemplate_name = 'course/delete_course.html'def get_success_url(self):return reverse('courses-list')

models.py

 class Course(models.Model):name = models.CharField(max_length=255,)def __str__(self):return ' '.join([self.name])class UserProfile(models.Model):user = models.OneToOneField(User)picture = models.ImageField(upload_to='profile_images', blank=True)class Meta:permissions = ( ('add_course', 'Add course'), )def __unicode__(self):return self.user.username

This is what I tried. First of all I get an error

NameError: global name 'user' is not defined.

And secondly I still don't think this would work :)

Answer

Something that i did for one of my django project is :

I defined a function that will check permissions and if user is authenticated :

from django.contrib.auth.decorators import user_passes_testdef group_required(*group_names):"""Requires user membership in at least one of the groups passed in."""def in_groups(u):if u.is_authenticated():if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:return Truereturn Falsereturn user_passes_test(in_groups, login_url='403')

And then i passed this function as decorator for my functions :

from whatever import group_required@group_required('Professor')
def action_only_for_professor(request):# do things@group_required('Student')
def action_only_for_student(request):# do other things

With this method you can declare multi-group for your functions like this :

@group_required('Professor', 'Student', 'Administrator', ...)

This trick work only with method that you create. if you want to do the same for class, i suggest you to check django-braces (e.q. http://django-braces.readthedocs.org/en/latest/index.html). Django Braces works like this :

from braces.views import GroupRequiredMixinclass CreateCourseView(CreateView, GroupRequiredMixin):group_required = u"Professor"def get_queryset(self, request):if not request.user.is_superuser:return Falsemodel = Coursetemplate_name = 'course/edit_course.html'fields = '__all__'def get_success_url(self):return reverse('courses-list')def get_context_data(self, **kwargs):context = super(CreateCourseView, self).get_context_data(**kwargs)context['action'] = reverse('courses-new')return context

If you want to use more than one group permission in your class, just do it like this :

group_required = [u"Professor", u"Student", u"Administrator", etc...]

Django-braces is very powerful to check permissions for your class, in the sense that you can check if a user is authenticated (with LoginRequiredMixin), is anonymous (AnonymousrequiredMixin), is superuser (SuperuserRequiredMixin), got one (PermissionRequiredMixin) or multiple permissions (MultiplePermissionRequiredMixin), and more and more stuff ! You just have to inherit your class with the appropriate mixin you want to use ;)

Hope it will help, and waiting for your return about all that :)

https://en.xdnf.cn/q/70534.html

Related Q&A

How to (properly) use external credentials in an AWS Lambda function?

I have a (extremely basic but perfectly working) AWS lambda function written in Python that however has embedded credentials to connect to: 1) an external web service 2) a DynamoDB table. What the fu…

How to set environment variable TF_Keras = 1 for onnx conversion?

Recently updated to tensorflow 2.0 and am having trouble getting my .h5 models into .onnx . Used to be a very simple procedure but now I am having an issue. When I run the following code:# onnx testing…

Django App Engine: AttributeError: AnonymousUser object has no attribute backend

I am using djangoappengine. When I try create a new user, authenticate that user, and log them in, I get the following error AttributeError: AnonymousUser object has no attribute backend.My code is sim…

python identity dictionary [duplicate]

This question already has answers here:Closed 12 years ago.Possible Duplicate:How to make a python dictionary that returns key for keys missing from the dictionary instead of raising KeyError? I need…

Whats a good library to manipulate Apache2 config files? [closed]

Closed. This question is seeking recommendations for books, tools, software libraries, and more. It does not meet Stack Overflow guidelines. It is not currently accepting answers.We don’t allow questi…

AttributeError: module object has no attribute webdriver

AttributeError: module object has no attribute webdriverwhy this error happen when write import selenium and when write code like this no error happenfrom selenium import webdriver

Mask Ocean or Land from data using Cartopy

I would like to mask the Land area from Sea Surface Temperature Data over the globe. I am using Cartopy to plot the data.import numpy as np import matplotlib.pyplot as plt import cartopy.crs as ccrs fr…

How to map func_closure entries to variable names?

I have a lambda object that is created in this function:def add_url_rule(self, rule, endpoint=None, view_func=None, **options):self.record(lambda s:s.add_url_rule(rule, endpoint, view_func, **options))…

How to use the convertScaleAbs() function in OpenCV?

I am trying to convert an image back to grayscale after applying Sobel filtering on it. I have the following code: import numpy as np import matplotlib.pyplot as plt import cv2image = cv2.imread("…

Register a Hello World DBus service, object and method using Python

Im trying to export a DBus service named com.example.HelloWorld, with an object /com/example/HelloWorld, and method com.example.HelloWorld.SayHello that prints "hello, world" if the method i…