1

So I have just begun learning the Django framework, and I am trying to make a basic application using AJAX to load Django responses into my main 'Content' div. So far so good, but one issue I am having is referencing JS/CSS files. All I want is a link to one CSS file, and one JS file in my main index page.

What I am hoping to do is add a reference to style/main.css and js/main.js in my application's urls.py script, where python would return the contents of the file. So, a standard <link src='style/main.css' ... /> tag would receive the contents of the appropriate file.

Thanks.

2
  • Are you trying to dynamically compute some values for the CSS/JS files or just to serve them off the disk? Commented Dec 19, 2011 at 1:30
  • Just simply serve them off the disk, I just cannot find the proper way to accomplish this Commented Dec 19, 2011 at 1:46

3 Answers 3

1

Read the documentation on serving static files. Essentially, you can use Django to serve these files during development, but should definitely configure your web server (e.g. Apache) to serve them directly in your production environment.

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

Comments

0

Setup "django.contrib.staticfiles" properly.

Add your link and script tags to your template using your STATIC_URL setting.

<link href="{{ STATIC_URL }}css/main.css"/>
<script src="{{ STATIC_URL }}js/main.js"></script>

https://docs.djangoproject.com/en/1.3/ref/contrib/staticfiles/

Comments

0

You can try these steps:

  1. open your settings.py and

    -add this at the first line of your file:

    import os.path

    -change your STATIC_ROOT's value to:

    STATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')

    -change your STATIC_URL's value to:

    STATIC_URL = '/static/'

  2. create a folder named "static" in your project root.

  3. create a folder for your static files like css, javascript and etc. I recommend you use a different folder for different types of files.
  4. open the urls.py of your project -add this to your imports: import settings -add this to the url patterns:

    (r'(?:.*?/)?(?P(css|jquery|jscripts|images)/.+)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT }),

    NOTE: In this example, there are folders named css, jquery, jscripts and images inside my static folder.

  5. In your template add this:

for css files: (in this example, default.css is the name of the css file)

<link href="/{{ STATIC_ROOT }}css/default.css" rel="stylesheet" type="text/css" media="all" />

for javascript:

<script type="text/javascript" src="/{{ STATIC_ROOT }}jquery/jquery.js"></script>

Comments

Your Answer

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