Reputation: 1
I have a Building
model and in that i have a field notes
which has GenericRelation
to GeneralNote
. In Building
admin added GeneralNotes
as Inlines. Now I want that the GeneralNotes
is editable for the user who is owner of general note.
class Building(TimeStampedModel):
name = models.CharField( unique=True, max_length=100, verbose_name=_("Building Name"), help_text=_("This is the name of your building")
)
notes = GenericRelation(GeneralNote)
class GeneralNote(TimeStampedModel):
owner = models.ForeignKey(
CompanyEmployee,
blank=True,
null=True,
# related_name='noteOwner',
on_delete=models.SET_NULL,
verbose_name="Note Owner",
)
content = models.TextField(max_length=400, null=True )
date_of_action = models.DateField(null=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
attached_to = GenericForeignKey()
In admin.py
:
class BuildingAdmin(ImportMixin, GeneralNotesIncludedAdmin):
inlines = (GeneralNoteInLine,)
class GeneralNotesIncludedAdmin(CoreBaseAdmin):
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
if not instance.owner:
instance.owner = request.user.companyemployee
instance.save()
super().save_formset(request, form, formset, change)
class CoreBaseAdmin(admin.ModelAdmin):
save_on_top = True
Upvotes: 0
Views: 274
Reputation: 4603
You can use the has_change_permission
method:
class GeneralNotesIncludedAdmin(CoreBaseAdmin):
def has_change_permission(self, request, obj=None):
if obj is None:
return True
return obj.owner == request.user.companyemployee
You can also add these to InlineModelAdmin
:
class GeneralNoteInLine(InlineModelAdmin):
def has_change_permission(self, request, obj=None):
if obj is None:
return True
return obj.owner == request.user.companyemployee
Upvotes: 1
Reputation: 313
You can use django-guardian and use guardian admin integration.
Upvotes: 0