简体   繁体   中英

Serving static files from root of Django development server

My goal is to have an Angular project being served from the root of my development server. The files will be completely static as far as Django is concerned, no Django template processing is needed. The angular project will then make resource calls to a Django project located at /api/ on the same development server, which will then return json results generated from a view for the Angular project to process.

I assumed it would be as easy as adding the following to my urls.py file.

url(r'^/', 'django.views.static.serve', {
        'document_root':'/Users/kyle/Development/project/site/app',
}),

Or

+ static("^/$", document_root="/Users/kyle/Development/project/site/app")

To the end of the urlpatterns.

With /project/site/app being the directory with the Angularjs files.

However, both of these leave me with 404 errors.

I'm open to changing the structure of the project if a more obvious solution exists.

You need to serve both index.html and your static files on / which is done like this in Django 1.10:

from django.contrib.staticfiles.views import serve
from django.views.generic import RedirectView

urlpatterns = [

    # / routes to index.html
    url(r'^$', serve,
        kwargs={'path': 'index.html'}),

    # static files (*.css, *.js, *.jpg etc.) served on /
    url(r'^(?!/static/.*)(?P<path>.*\..*)$',
        RedirectView.as_view(url='/static/%(path)s')),
]

See this answer where I wrote a more complete explanation of such a configuration – especially if you want to use it for production.

It turned out that it was a combination of 2 things, as shavenwarthog said, it shouldn't have the slash. Also, it needed a regular expression to direct it to the file. The final line ended up being:

url(r'^(?P<path>.*)$', 'django.views.static.serve', {
        'document_root':'/Users/kyle/Development/project/site/app',
}),

I can then access files like

http://localhost/beer.jpg
  1. note that by default Django won't serve a directory listing. Do you still get a 404 if file /Users/kyle/Development/project/site/app/beer.jpg doesn't appear as http://localhost/beer.jpg ?

  2. in urls.py URLs don't start with a slash; compare url(r'beer') with url(r'^/beer')

I suggest just going for the standard STATIC support. It's awkward, but lets you serve file simply during development, and switch to a 3rd party server (ie Nginx) for production:

https://docs.djangoproject.com/en/dev/howto/static-files/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM