Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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

EDIT: I need to create specific permission. So only users with this permission can change specific field of model. I just need make one field 'readonly' for some users. Is it possible in django?

like image 830
Michal Drozd Avatar asked Oct 30 '10 18:10

Michal Drozd


1 Answers

Creating a perm without using DB means you do not want to use django permission system. In that point, I would ask why you do not want to use it?

If it is ok to use django permission sywstem, you can create a permission and check it by overrriding admin save method... Like:

in your 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 get the state of related record before you save it and check for related permission. If the user do not have required perm. then you replace your field's value with the previous one. If this is a new record, then you set that field to any value you want.

like image 156
FallenAngel Avatar answered Oct 10 '22 19:10

FallenAngel