Michal Drozd
Michal Drozd

Reputation: 1351

How to create custom permission (user role) in 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?

Upvotes: 6

Views: 13733

Answers (2)

Mp0int
Mp0int

Reputation: 18737

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.

Upvotes: 7

zsquare
zsquare

Reputation: 10146

You could check out django-authority. It lets you implement object level permissions, and even logical checks. Logical checks are not stored in the database, but are functions that can be passed values and return True or False. Shameless plug: my fork implements the django 1.2 object permission backend, so you could use it like: userA.hasperm("see_xyz")

Upvotes: 0

Related Questions