Jean Zombie
Jean Zombie

Reputation: 627

Wagtail: How to overwrite create/edit template for PageModel

I want to overwrite create.html and edit.html used for models derived from Wagtails 'PageModel'.

If I understand the docs correctly it should be as simple as specifying the attributes:

class MyAdmin(ModelAdmin):
    model = MyPage
    create_template_name = "myapp/create.html" 
    edit_template_name = "myapp/edit.html"

My templates are located at projectroot/templates/myapp. It works fine if my model is a Django model but for a PageModel based model the create view still uses wagtailadmin/pages/create.html. I also tried the other location patterns mentioned in the docs w/o success.

Is it possible to change the edit and create templates for a PageModel? Or do the same limitations as for views apply, i.e. only index.html and inspect.html can be overwritten?

Upvotes: 1

Views: 2149

Answers (1)

LB Ben Johnston
LB Ben Johnston

Reputation: 5176

ModelAdmin does not provide create, edit, or delete functionality for Page models, as per the documentation note.

NOTE: modeladmin only provides ‘create’, ‘edit’ and ‘delete’ functionality for non page type models (i.e. models that do not extend wagtailcore.models.Page). If your model is a ‘page type’ model, customising any of the following will not have any effect.

It can be a bit confusing as the ModelAdmin system would seem to work for page models also, but there are some other ways to modify how your page can be edited. These will not be scoped to the ModelAdmin area though.

Option 1 - customise the generated form for your MyPage model

Example

from django import forms
from django.db import models

from wagtail.admin.forms import WagtailAdminPageForm
from wagtail.core.models import Page


class EventPageForm(WagtailAdminPageForm):
      # ...


class MyPage(Page):
    # ...
    base_form_class = MyPageForm

Option 2 - customise the view via hooks

To customise the create & edit views for the normal (e.g. clicking edit page on the Wagtail user bar or explorer) page editing interface, you will need to use Wagtail hooks. Here you have access to the request so you will likely be able to determine if you are in the ModelAdmin area.

Create a file called wagtail_hooks.py in your app folder and provide a hook that will return a custom response (this will need to be rendered by your custom view.).

There are separate hooks for before_create_page and before_edit_page

Example from before_create_page docs below.

from wagtail.core import hooks

from .models import AwesomePage
from .admin_views import edit_awesome_page

@hooks.register('before_create_page')
def before_create_page(request, parent_page, page_class):
    # Use a custom create view for the AwesomePage model
    if page_class == AwesomePage:
        return create_awesome_page(request, parent_page)
```python

Upvotes: 1

Related Questions