Setting permissions between edit and view only in wagtail
In my Wagtail project, I have a class that inherits from EditView(modelAdmin). Within this class, I override the get_edit_handler method to dynamically set fields as read-only based on user permissions. However, I'm encountering an issue with RichTextField fields: the permission settings only take effect after restarting the application. For example, if I set an InlinePanel to read-only, all InlinePanel instances that include RichTextField fields across the model also become read-only, regardless of their individual permission settings.
class JournalEditView(EditView):
def form_valid(self, form):
self.object = form.save_all(self.request.user)
return HttpResponseRedirect(self.get_success_url())
def get_edit_handler(self):
"""
Overrides the get_edit_handler method from EditView.
It checks whether the user has permission to edit each field.
If not, the fields for which the user lacks the journal.can_edit_{field_name}
permission in their user_permissions will be set as read-only.
This applies to FieldPanel, AutocompletePanel, and InlinePanel.
"""
edit_handler = super().get_edit_handler()
user_permissions = self.request.user.get_all_permissions()
if not self.request.user.is_superuser:
for object_list in edit_handler.children:
for field in object_list.children:
if isinstance(field, FieldPanel) and f"journal.can_edit_{field.field_name}" not in user_permissions:
field.read_only = True
elif isinstance(field, InlinePanel) and f"journal.can_edit_{field.relation_name}" not in user_permissions:
field.classname += ' read-only-inline-panel'
for inline_field in field.panel_definitions:
inline_field.read_only = True
return edit_handler
class JournalAdmin(ModelAdmin):
model = models.Journal
inspect_view_enabled = True
menu_label = _("Journals")
create_view_class = JournalCreateView
edit_view_class = JournalEditView