Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 460
Kyle Swanson Avatar asked May 29 '14 17:05

Kyle Swanson


3 Answers

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.

like image 177
metakermit Avatar answered Sep 24 '22 07:09

metakermit


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
like image 28
Kyle Swanson Avatar answered Sep 20 '22 07:09

Kyle Swanson


  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/

like image 33
johntellsall Avatar answered Sep 20 '22 07:09

johntellsall