Reputation: 3560
I need to set permission as per registered user using Django and Python. I have done something but confused whether it is fulfilled my requirement or not. I am providing my code below.
class Control(models.Model):
"""docstring for Control"""
user_id = models.ForeignKey(User)
control_reactor = models.IntegerField(default=0)
find_reactor = models.IntegerField(default=0)
view_reactor = models.IntegerField(default=0)
class Meta:
"""docstring for Meta"""
permissions = (
("view_reactor", "can view reactor"),
("find_reactor", "can find reactor"),
("controll_reactor", "can controll reactor"),
)
I am access those permission using Django decorator function like @permission_required
. Here I need as per user I will set the 3 permissions but confused that this model class is doing as per requirement.
Upvotes: 1
Views: 4259
Reputation: 9931
The meta class defined is just a representation that your model will have only these permissions so it becomes manageable.
You can create permissions programmatically using Permission class from django. From django docs
User objects have two many-to-many fields: groups and user_permissions. User objects can access their related objects in the same way as any other Django model
Permission models stores all the permission which can be set to a specific user. All you have to do is add the create a permission and add it to user.
from django.contrib.auth.models import Permission, User
content_type = ContentType.objects.get_for_model(BlogPost)
permission = Permission.objects.get(
codename='change_blogpost',
content_type=content_type,
)
user.user_permissions.add(permission)
The related name is user_permissions
so you can directly add the permission same as M2M relationships.
Now suppose you want to check permissions
user.has_perm('app_name.code_name') # generic example
user.has_perm('myapp.change_blogpost')
Now for decorator you can do same
@permission_required('app_name.code_name')
EDIT: Generally you grant permission when you create a user so the example mentioned above can be put in your views where you signup the user. If you don't want to grant permissions right away then you can make a separate view which grants permission to the user
def grant_permissions(request):
user = request.user
# then you put the code mentioned above
for your case you can either create permissions in you code using permissions model or use meta class.
Just migrate the database to create permissions defined in the meta class. After migrate don't forget to give permission to user using the code mentioned above using Permissions model Then you can use the permissions in the decorator.
@permission_required('view_reactor')
Upvotes: 4