Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you give a wagtail/django Page a custom url to serve at?

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.

like image 294
goosefrumps Avatar asked Sep 07 '17 23:09

goosefrumps


People also ask

How do I reference a URL in Django?

Django offers a way to name urls so it's easy to reference them in view methods and templates. The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py .

Can we directly import a function in URL in Django?

Django allows for easy transports of functions, pages, data, etc, from one page to another pretty easily. So, for example, we can import a function from the views.py file into the urls.py file. So, this is what is meant by importing a function.

What is URL mapping in Django?

It's where you define the mapping between URLs and views. A mapping is a tuple in URL patterns like − from django. conf. urls import patterns, include, url from django.


1 Answers

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'),
]
like image 99
rgs258 Avatar answered Oct 26 '22 18:10

rgs258