1

Hey guys - I am having trouble setting up my Django urls file correctly for the following thing!

<script type="text/javascript" src="/javascript/HashMap.js"></script>

What happens is the file is attempted to get found : http://localhost/javascript/HashMap.js but this URL does not match any within the URL Config and therefore the GET request fails.

Can anyone lend a hand to help me find the correct line to add to allow this kind of thing to work!

Cheers

Andy

3 Answers 3

3

You need to serve your JavaScript as a static file.

How you do this in production depends on what Web server you're running with. Django doesn't normally serve up static files.

For example, for Apache, you'd put this in your Apache config:

Alias /javascript/ /usr/local/wsgi/static/javascript/

Then you can put your .js files in the directory referenced.

The Django docs have a entire page on just this topic (serving static files): http://docs.djangoproject.com/en/dev/howto/static-files/

Sign up to request clarification or add additional context in comments.

2 Comments

Aha - I see - I think this will be what has to happen. Django can serve static files then - but its bad practice... any reason in particualar its bad practice. Having to do apache configs and files all over the place with an alias seems like a poor solution.
It's just not designed for that (static file serving efficiently). It's fine for development, but not recommended in production.
1

Javascript is usually considered a static resource file. If that's true in your case, I would refer you to the Django documentation. If you really need to use urlconfs to point to a view that generates Javascript, then you will need to make an entry in your URLconf for it and point it to a view.

Comments

0

If you're trying to get only the file as static content, the problem will be surely at your MEDIA_ROOT and MEDIA_URL settings variables. Just check they're pointing to where the javascript file is and your MEDIA_URL should have a postfix to ensure that you're accessing an "special" directory where the media files are stored.

In the case you're trying to do some processing over the file, generating it at runtime, etc. try with this regular expression:

r'^javascript/(?P<jsfile>.+\.js)$'

In your view declaration, instead of only get the request as parameter, you will have the request and a new param called jsfile, that is the filename you'requesting. So in the view, do the processing and return an HttpResponse object with the processed file contents.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.