A simple example of Django and CSS

前端 未结 5 2032

I\'m new to Django, and am trying to set up a really simple Django app.

Now, I\'m up to chapter 5 in the Django online book : http://www.djangobook.com/en/2.0/chapte

5条回答
  •  难免孤独
    2020-12-08 03:12

    The handling of static files has changed significantly (for the better) in Django 1.3. In particular is the flexible difference between static files (think code required CSS/JS/images) and media files (think images uploaded by users in the use of you application). The staticfiles app handles what you are asking for.

    Put django.contrib.staticfiles in your settings.py INSTALLED_APPS. Then create a static directory inside your app directory - so project/app/static/. Within that static directory organize your support files as you like (css/, js/, images/, icons/, etc). staticfiles by default will look in the static/ directory for every app listed in INSTALLED_APPS. Not just your own, but all the Django apps and third-party apps. (sidenote: the Admin in Django 1.4 moves to this paradigm while in 1.3 it still uses the ADMIN_MEDIA_PREFIX).

    The staticfiles app knows about all those static/ directories in all the apps but it needs to collect all that content in order to serve it. In development, when using manage.py runserver it is handled for you. Django will run your site and automatically deliver all the static content from all the static sources. (Sources, as mentioned in another answer, are set in the STATICFILES_FINDERS setting.) When not using runserver, use manage.py collectstatic to gather all the static files into the folder defined in STATIC_ROOT. Keep this directory empty. It is a collection destination. Of course your web server will need to be configured to serve this directory.

    Now there is one more piece - the view. This is where the STATIC_URL comes into play. When referring to static files in your templates, the easiest way is to use {{ STATIC_URL }}. Django by default makes that variable available to any view using the RequestContext. Do something like this - .

    For more information and more ways to refer to STATIC_URL in your templates, check out this answer to a similar question.

提交回复
热议问题