p0llard
p0llard

Reputation: 459

Django: User can only edit or delete objects tied to their account

There is a similar question to this, but it requires the use of tastypie - I'm looking for a way to do this without any additional add-ons.

I'm trying to create a system where users can only edit objects tied to their account.

models.py:

class Item(models.Model):
    ...
    author = models.ForeignKey(User)
    ...

I would like a system whereby only the user specified in the author field is able to edit or delete the object. This doesn't seem (to me) to be possible using the default admin system. I could implement it by writing my own admin page which checks whether a user is authorised to delete a specific object, but It would be better if there were another way.

Upvotes: 2

Views: 2557

Answers (1)

Jamie Cockburn
Jamie Cockburn

Reputation: 7555

You need to create a ModelAdmin instance for your model(s) and override the appropriate methods:

class MyModelAdmin(admin.ModelAdmin):    
    def has_add_permission(request):
        # Should return True if adding an object is permitted, False otherwise.

    def has_change_permission(request, obj=None)
        # Should return True if editing obj is permitted, False otherwise.
        # If obj is None, should return True or False to indicate whether editing of objects of this type is permitted in general 

    def has_delete_permission(request, obj=None)
        # Should return True if deleting obj is permitted, False otherwise.
        # If obj is None, should return True or False to indicate whether deleting objects of this type is permitted in general

Upvotes: 2

Related Questions