2013年9月28日星期六

Crusher Django Tutorial(6) Load Static Files In Django

Cute and hate ADs: A website I made for sale py-cone-crusher(For god sake help me click it or just ignore it.55555555)

Welcome to the sixth Django Tutorial -- how to load css file and pic file in Django.It is easy in html or php,but in Django we have to do some job but it not very hard.

First,we need to new a folder named static, and with it we use the css frame-work BootStrap which is awesome!

Then, we edit the urls.py:

 
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from django.conf.urls.defaults import *
from hello.TomAndJerry.views import *  # import all the funtions, we have only one

import os   # import os

from django.contrib import admin   # import admin
admin.autodiscover()               # add this to make admin discover

static = os.path.join(os.path.dirname(__file__), 'static')

urlpatterns = patterns('',
    (r'^$', show),  # conf the function
    (r'^just_show/$', just_show),
    (r'^info/(.+)/', info),
    (r'^info/$', info),
    (r'^admin/', include(admin.site.urls)), # add this line to conf admin page url
    (r'^static/(?P<path>.*)$', 'django.views.static.serve',
    { 'document_root': static }),      # conf the static root
)
 

The last step is add the link tag in the TomAndJerry.html template file:

 
<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <link rel="stylesheet" href="/static/bootstarp.css" type="text/css" media="screen" title="no title" charset="utf-8" />
        <link rel="stylesheet" href="/static/bootstrap-responsive.css" type="text/css" media="screen" title="no title" charset="utf-8" />
        <title>Tom And Jerry</title>
        
    </head>
    <body>
        <h1>Tom And Jerry Show</h1>
        <p>
            Tom And Jerry is a carton show which is Cool, I know this is sounds
            silly...
        </p>
        <h2>{{ title }}</h2>
        <ul>
        {% for player in players %}
            <li>{{ player }} is a player.</li>
        {% endfor %}
        </ul>
        {% if same %}
            <p>
                No one win...
            </p>
            <img src="/static/black.png" alt="black png file" title="black png file" width="156" height="155" />
        {% else %}
            <p>
                Tom Win the game!
            </p>
             <img src="/static/hello.png" alt="hello django png" title="this is a png file" width="170" height="167" />
        {% endif %}
    </body>
</html>
 

As you can see, we load the css file from the static folder and remove the css code in the html which will make our code more clean. And we load the img by the player who win.That is also not hard to understand. Let's just test our result:

BTW, the bootstrap-responsive.css is for the Responsive Web Design which is cool!

Well, that is what we learn today,in the next post we will learn the Form in Djang.

没有评论:

发表评论