سؤال

I'm using django 1.3 for production and want to use static file's in my CSS and javaScript but it doesn't work , I don't have any problem in my HTML ! how must solve this problem ? I didn't find any solution in django doc .

I use this code for adding static files to my CSS :

{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
#main {
     background-image: url("{{ STATIC_PREFIX }}img.png");
}

I'm using this template tag {% load static %} {% get_static_prefix as STATIC_PREFIX %} in my html and it works fine but I dunno why it doesn't work in CSS !!!

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

المحلول

Your CSS files aren't rendered by the Django templating engine, they are just served by your web server, so you can't use the Django template language.

If you really wanted to (and this is an exceptionally bad idea) you could serve you CSS files through Django by creating URLs and views that render the CSS files, allowing you to make use of the template language.

نصائح أخرى

The documentation for static CSS and image files is here: Current Django Documentation and Django Documentation 1.3.

In your settings.py you'll want to set

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    '/full/page/to/static/',
)

Then you can store your images and css files under that '/full/page/to/static/' directory. In your template you would use your css and images like this:

<link rel="stylesheet" type="text/css" href="/static/styles.css">
<img src="/static/header.png" alt="Company Header" />

In addition to that you can add a directory structure under the "/static/" directory and it will reflect in URL.

For example

/full/path/to/static/img
/full/path/to/static/css

Would resolve to:

    <link rel="stylesheet" type="text/css" href="/static/css/styles.css">
    <img src="/static/img/header.png" alt="Company Header" />
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top