سؤال

Let's suppose I have an HTML page (base.html) that must include one JavaScript file.

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

It is my understanding that a Django project is not hosted in a public folder. Rather, requests are routed to views.py which generates a response.

Let's suppose my project directory looks like this

- project
- project_app
    - views, models, ecc…
- templates
    - base.html
    - css
        - main.css
    - js
        - main.js

How come base.html can reference main.css and main.js? If I access myserver.com/js/main.js this should not return anything (as the template folder is not public). Yet the browser need to access those file and I need to include them.

Do I need to write a specific URL rule to redirect requests to /js/main.js to the actual js file or what sort of magic can make a simple html include works?

هل كانت مفيدة؟

المحلول

The usual method is to keep your CSS, javascript, and similar files in a static folder and serve them to your html. General Django documentation can be found here.

In a nutshell, your directory will look like this:

- project
- project_app
    - views, models, ecc…
- templates
    - base.html
- static
    - css
        - main.css
    - js
        - main.js

Then, your base.html will reference the file using:

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

The docs I referenced at the top show how to serve static files in production. Lots of people use a content delivery network (CDN) to serve their static files. Amazon's S3 service is an example of this. Then, you'll change the STATIC_URL setting in your settings.py to your S3 bucket (or similar network). You can then reference the STATIC_URL in your templates.

{% load static %}
...
<script type="text/javascript" src="{% static 'js/main.js' %}"></script>
...

You'll use commands like ./manage.py collectstatic to collect your static files and move them to your CDN at certain times. Basics of collectstatic can be found here.

نصائح أخرى

You need to put all your static files in STATIC_ROOT folder by using command django-admin.py collectstatic and serve this folder. More details and explanation you can find here:

https://docs.djangoproject.com/en/dev/howto/static-files/#managing-static-files-css-images

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top