Django serve static index.html with view at '/' url

后端 未结 5 2023
面向向阳花
面向向阳花 2020-12-25 11:14

I have my index.html in /static/ folder. My django app is running ok when i try:

http://127.0.0.1:8000/index.html

But i want to acces index

5条回答
  •  粉色の甜心
    2020-12-25 11:42

    You can serve static/index.html for development like this:

    if settings.DEBUG:
        urlpatterns += url(
            r'^$', 'django.contrib.staticfiles.views.serve', kwargs={
                'path': 'index.html', 'document_root': settings.STATIC_ROOT}),
    

    But for production you should configure your nginx (or other frontend server) to serve index.html file for / location

    UPDATE

    I want to explain the case you should do like this. For example your django app is only admin and api view, but client interacts with a single page app (Ember, Angular, whatever). So you project has at least two subprojects, one with your main django app and the second is a client app with all html/js/css stuff. It is very convenient to have client scripts separate from django backend, it allows your frontend developers to do their job and avoid django existence (someday it can be moved to the distinct repo).

    So in this case you get the following build workflow:

    1. Run client app sources watcher to rebuild your scripts/styles/templates (brunch watch, grunt job or gulp watch task)
    2. Collect static with django for production
    3. Make sure you have urlpatterns fix for developments and right nginx config for production

    Here is my urls.py example

    urlpatterns += patterns(
        'django.contrib.staticfiles.views',
        url(r'^(?:index.html)?$', 'serve', kwargs={'path': 'index.html'}),
        url(r'^(?P(?:js|css|img)/.*)$', 'serve'),
    )
    

提交回复
热议问题