Skip to content

Instantly share code, notes, and snippets.

@vossisboss
Created November 1, 2023 19:40
Show Gist options
  • Select an option

  • Save vossisboss/a4c452a266a0d72c14edcf8cc05d1f7b to your computer and use it in GitHub Desktop.

Select an option

Save vossisboss/a4c452a266a0d72c14edcf8cc05d1f7b to your computer and use it in GitHub Desktop.
Example Django Headless URL configuration
# This code example was provided by Ed Rivas from Oddbird. You can find him on Github at https://github.com/jerivas/
# Ed says that jsreverse is a helper he finds useful that exposes Django URLs in JS. You can find that package here: https://pypi.org/project/django-js-reverse/
# Ed says the websocket settings are optional and only really needed if you have some realtime endpoints
# The most important part, according to Ed, is TemplateView at the bottom, which is a catchall for all requests that don't match the prior URLS and loads the frontend.
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include("api.urls")),
path("jsreverse/", urls_js, name="js_reverse"),
# Add WebSocket routes so that non-HTTP paths can be accessible by
# `reverse` in Python and `window.api_urls` in JavaScript. These will
# usually only be the path component, not a full URL, and so the caller
# will have to build them with the right scheme and authority sections.
*websockets.routes,
*static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT),
# Catchall for the rest. Always render index.html so the frontend takes over
re_path(
r"^",
TemplateView.as_view(template_name="index.html"),
name="frontend",
),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment