Search code examples
djangomithril.js

Django vs Mithril url routing


I am using routing via Mithril. When I route to mysite.com/subpage/item3 via javascript, the static file '/static/app.bundle.js' remains loaded and the subpage html is shown, as expected.

m.route(document.body, "/", {
    "/": Home,
    "/subpage": Subpage,
    "/subpage/:focus": Subpage,
    "/:focus": Home
});

However, when I navigate to mysite.com/subpage/item3 from initial page load, Django kicks in and attempts to load the static file from '/subpage/static/app.bundle.js' instead. This results in a 404 error. I have set STATIC_URL and STATICFILES_DIRS, and I don't understand why Django is changing them.

Here's my url pattern:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('<url>', views.index, name='index'),
    path('<url>/<suburl>', views.index, name='index')
]

Here's my static file settings:

STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)

Thank you!


Solution

  • Your <script>'s src attribute contains a relative URL, which is the behavior you're seeing. This how HTML works. To "fix" it, make it absolute:

    <script type="text/javascript" src="/static/app.bundle.js" type="module"></script>
                                        ^----add this
    

    Manually constructing the URL has the downside of completely bypassing Django's STATIC_URL setting and preventing you from transparently switching to a different URL in production. I suggest you read through the Django documentation on static files. In the end, you will be able to do this:

    <script type="text/javascript" src="{% static "app.bundle.js" %}" type="module"></script>