I have a model which looks like this:
class Change(models.Model):
RFC = models.CharField(max_length=10)
Ticket_Number = models.CharField(max_length=10)
Plan_Owner = models.ForeignKey(User)
I then register the model in the Django admin via this:
class ChangeAdmin(admin.ModelAdmin):
search_fields = ('RFC', 'Ticket_Number','Plan_Owner')
list_display = ('RFC', 'Ticket_Number','Plan_Owner')
fieldsets = [
('Ticket Details', {
'fields': ['RFC', 'Ticket_Number', 'Plan_Owner']}),
]
admin.site.register(Change, ChangeAdmin)
What I want to achieve is to ensure that the Plan_owner for a particular change is the only one who can edit it apart from a superuser. Everyone can view it, but the plan owner is the only one who can make changes to it.Also by editing I mean, he can do ever thing but delete a row. I have had a look at Django guardian and it does exactly what I want but one has to manually set the permissions in guardian for each row. I am looking for a solution wherein these permissions are automatically set as per my requirements ...
I wouldn't use object-level permission for something as simple as your requirement. You just need to have an
owner
ForeignKey to your Model and only allow the owner of each object to modify it (you can use thePlan_Owner
-- PLEASE change it toplan_owner
andTicket_Number
toticket_number
to be compatible with pep 8 and django style guide).I have written a post that describes how to do this in django:
http://spapas.github.io/2013/11/05/django-authoritiy-data/
Actually I am describing how to use authorities that users belong to and each user can edit the objects of his authority but your requirement is covered.
Update
For completeness, I am adding the implementation here:
Your Create and Update Class Based Views have to pass the request to your forms and also your Detail and Update CBV should allow only getting objects that belong to the user (let's suppose that your model is named
UserData
:It checks if the
request.user
has permission (is the owner of the object) and also passes therequest
to theModelForm
. Thehas_access
function defined above just checks if the current user is the owner of the object:Yot ModelForm should be like this (same for create/update):
It removes
request
fromkwargs
and sets it as an attribute and at save it sets the owner of the object to thereqest.user
.