6

In wagtail/django how do you make a basic wagtail Page model, create the html template, and then tell that model to serve as a view for a specific url?

from django.db import models
from wagtail.wagtailcore.models import Page

class MyPage(Page):
  title = models.CharField(blank=True, null=True, max_length=255)
  #...

I want the url to register like

url(r'^monkey/(?P<slug>[A-Za-z0-9]+)$', ...)

But I don't have a common urls.py folder its stored outside of the project. I tried using the RoutablePageMixin, but I believe that serves for subpages. I also know where to store the html template within the structure so that is not a problem.

Astik Anand
  • 12,757
  • 9
  • 41
  • 51
  • 1
    Please can you give more details on why you don't have an accessible urls.py? That's a standard part of any Django project, and you're going to be a bit stuck if you can't edit it. – gasman Sep 07 '17 at 23:31

2 Answers2

2

You might want something like:

from django.http import Http404
from django.views import View
from wagtail.core.views import serve

class WagtailPageServeView(View):
    """
    A default way to serve up wagtail pages in urls
    """

    wagtail_slug = None

    def get(self, request, *args, **kwargs):
        if self.wagtail_slug:
            return serve(request, self.wagtail_slug)
        else:
            raise Http404(
                f"WagtailPageServeView missing 'wagtail_slug'. Cannot serve "
                f"request.path: {request.path}"
            )

Then you can do something like this in urls.py:

urlpatterns += [
    re_path(r'^$', WagtailPageServeView.as_view(wagtail_slug='/'), name='home'),
]
rgs258
  • 105
  • 1
  • 7
0

In Wagtail, you are creating a page type and then creating instances of the page type in the CMS.

Even if you are only going to use this page once, you still need to make a type. Following this logic, page urls are defined inside the CMS through the page's parent and slug. Most likely, you could achieve what you want through these means.

If you want to override your page template and create a custom url, you can override the get_url_parts method on your model.

Also, if you want to skip Wagtail for this page specifically, remember that Wagtail is just built over Django. You can always create a new module and define the url in that model. If you check your site urls.py, you will see the wagtail url patterns. You can change it to look something like this:

urlpatterns = [
    # other urls...
    url(r'wagtail/', include(wagtail_urls)),
    url(r'^monkey/', ('monkey_app.urls', 'monkey_app')),
]
jnns
  • 5,148
  • 4
  • 47
  • 74
jhoover4
  • 46
  • 1
  • 9