Search code examples
pythondjangowagtailwagtail-admin

Wagtail Admin: How to control where user is redirected after submitting changes for moderation


On a Wagtail site I've built, I have a model type that is editable by authenticated users who do not have full admin privileges. They can only save as a draft or submit the changes for moderation. The problem I'm having is that Wagtail is inconsistent about where it redirects after executing these two actions. Saving the Draft takes the user back to the edit screen they were just on, with a note saying the draft was saved (good). Submitting for Moderation returns the user to the admin browse view of the parent page, which shows all of the sibling nodes in a list. They can't edit the vast majority of items on that list, so I think this is confusing for a non-admin user. I would like to have the "Submit for Moderation" action detect whether the user belongs to a group other than admin (or, failing that, whether the page has unpublished changes, as in my code example below) and, if so, redirect them back to the edit screen just like "Save as Draft" does.

I tried this in my model definition and it didn't work:

def save(self, *args, **kwargs):
  #do some field value manipulations here before saving
  super().save(*args, **kwargs)
  if self.id:
    if self.has_unpublished_changes:
      return HttpResponseRedirect('/admin/pages/' + str(self.id) + '/edit/')

There's probably some sort of Wagtail admin action that I need to hook into and override, rather than trying to accomplish this in models.py, but I don't have much experience with this, so I need a better understanding of what to change and where.


Solution

  • Set up an after_create_page and after_edit_page hook: https://docs.wagtail.io/en/stable/reference/hooks.html#after-create-page

    To do this, add a wagtail_hooks.py file in one of the apps in your project. This is where you can define functions to be called after creating or editing a page through the admin, such as:

    from wagtail.core import hooks
    
    @hooks.register('after_create_page')
    def redirect_after_page_create(request, page):
        if not request.user.is_superuser:
            return HttpResponseRedirect('/admin/pages/' + str(page.id) + '/edit/')
    
    @hooks.register('after_edit_page')
    def redirect_after_page_edit(request, page):
        if not request.user.is_superuser:
            return HttpResponseRedirect('/admin/pages/' + str(page.id) + '/edit/')