Django user groups with decorators vs permission
I understand the basic user authentication, login, creating accounts, extending user model...
I am trying to create a site where teachers and students can login. Teachers would have access to pages students cannot access with rights to post homeworks ect...
I think it is possible to do this with:
- Assigning a user to a specific group upon creation.
- Using decorators to limit access to the appropriate group.
.
@login_required
@user_passes_test(not_in_student_group, login_url='/login/')
def some_view(request):
# ...
def not_in_student_group(user):
if user:
return user.groups.filter(name='Student').count() == 0
return False
note I got the above code from:
http://bradmontgomery.blogspot.com/2009/04/restricting-access-by-group-in-django.html
Question:
How does using permission differ from the above approach?
How can permissions be used, and how does defining permission help me achieve the above results? (If it is possible to do so, should it be used?)
开发者_开发技巧
It seems there are a hundred ways that people get to the same results in Django regarding authorization and permissions. Groups are one way, definitely.
Django permissions are usually based on your data, so "table based", or "row based". Row based permissions are not native to Django, you have to either roll your own solution, or use something like django-guardian or django-authority More Here.
The docs on permissions are here
class Quiz(models.Model):
title = models.CharField(max_length=64)
class Meta:
permissions = (
("can_take_quiz", "Can take quiz"),
("can_grade_quiz", "Can Grade Quiz"),
)
With this model, and these permissions, you could see that possibly a student aide would be given permission to grade a particular quiz, or a quiz for a given teacher, this is where row-based permissions would be useful. Implementing something like that (via has_permission) can solve a problem (and is more explicit) than just adding a user to a group.
You can add users to groups like you have already, and then give that entire group permissions to add a quiz, or grade quizes (teachers can add/edit/delete/grade, students can take) quizes, and check based on that.
then your user_passes_test would be user.has_perm('quiz.take_quiz')
or instead of a decorator, you could pass the specific quiz to your object based backend.
精彩评论