Search code examples
djangodjango-urlshtmx

How to include multiple urls.py from the same django app?


I'm new to django and htmx and was trying to keep my urls.py a bit more clean by putting all urls which just give a htmx response into another file. To include this file into my paths I used djangos include function, because I'd like to route all htmx-specific request over an url called /htmxFunctions/* The folder structur is:

project

  • base_project
    • urls.py
  • my_app
    • urls.py
    • htmx
      • htmx_urls.py

my url files look like this:

# base_project/urls.py
urlpatterns = [
    path("", include("my_app.urls")),
    path("admin/", admin.site.urls),
    path("__reload__/", include("django_browser_reload.urls")), #tailwind specific
]
#my_app/urls.py
urlpatterns = [
    path("", views.index, name="index"),
     ...
    # htmx-funktionen
    path("htmxFunctions", include("my_app.htmx.htmx_urls")),
]
my_app/htmx/htmx_urls.py
urlpatterns = [
    path("test", views.test, name="test"),
    path("", views.index, name="test"), # for testing purposes
]

My Problem is, using hx-post="/htmxFunctions/test/" only results in an 404 error. but the general include seems to work because just using hx-post="/htmxFunctions" gives the right response. Does someone know how to solve this problem?

Allready checked for spelling errors, tried porbably every combination of using slashes in the routes of hx-post and my path but nothing seems to work. Also tried namespacing but didn't really get what it is supposed to do.

 path(
        "htmxFunctions",
        include(("my_app.htmx.htmx_urls", "htmx"), namespace="htmx"),
    ),

Solution

  • Thanks to George I found my problem! My django path didn't end with a slash (I only used include with an empty string before and all my other paths we're endpoints so they didn't needed one. I forgot about it).

    ...
    # htmx-funktionen
        path("htmxFunctions/", include("my_app.htmx.htmx_urls")) 
    ...
    

    Now it works :)