How to create custom permission (user role) in Django?

I have a simple question. How to create a user role in Django without manually creating it?

EDIT: I need to create a special permission. Thus, only users with this permission can change a specific field of the model. I just need to make one read-only field for some users. Is this possible in django?

+6
python django
source share
2 answers

Creating a variable without using a database means that you do not want to use the django permission system. At this point, I would ask why you do not want to use it?

If it is ok to use sjwstem django permissions, you can create a permission and check it by overriding the admin save method ... For example:

in models.py

 class SomeModel(Model): your_spec_field = FieldType(...) class Meta: permissions = ( ("some_perm", u"A name for your default permission"), ) 

In your related admin.py

 class SomeModelAdmin(ModelAdmin): def save_model(self, request, obj, form, change): if change: curr_value = SomeModel.objects.get(pk=obj.id) if not request.user.has_perm('<your_app>.some_perm'): obj.your_spec_field = curr_value.your_spec_field else: if not request.user.has_perm('<your_app>.some_perm') obj.your_spec_field = '' # or the default value according to your field type obj.save() 

In this approach, you will get the status of the related record before saving it and checking for the appropriate permission. If the user does not have the required variable. then you replace your field value with the previous one. If this is a new entry, you will set this field to whatever value you want.

+7
source share

You can check django-authority . It allows you to implement object level permissions and even logical checks. Logical checks are not stored in the database, but are functions that can be passed to values ​​and returned True or False . Shameless plugin: my fork implements a backend for resolving a django 1.2 object, so you can use it as: userA.hasperm("see_xyz")

0
source share

All Articles