2013年9月23日星期一

Crusher Django Tutorial(3) Using Template

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

In the previous post,we learn the basic url conf in Django,I am appreciative that @Will Farley and @Nathan Cox,they told me that the Virtualenv and pip,I google them,I still don't know the advantages of them.If you want you can see here about the pip,that helpful for your site-packets manage.BTW,if you know the advantages of pip,maybe you can tell me.

In fact you can just using the following command to install with network,of course:


zoo@ubuntu:~/Desktop$ sudo apt-get install python-virtualenv

zoo@ubuntu:~/Desktop$ sudo pip install django

Well, in this tutorial, we will learn the Templates System in Django. Now,we need start An App first, and then using the App for the real job,but not just have a fun with Django. First,we can forget the views.py,and start an app with the command in our hello project:


zoo@ubuntu:~/hello$ python manage.py startapp TomAndJerry

Using App can make the manage easy and make your project more logical,here we create a TomAndJerry project.You can see that there are four files

  • The __init__.py will make the TomAndJerry as a packet.
  • The test.py, I don't know maybe just unit test of the App.
  • The models.py, that is the class we designed in MTV(model,templates,view).
  • The views.py that we know, the function we create function to control the Logic.

After create our App,we need to tell the settings.py that we have create it (I wonder why the Django can not add it...), just edit the settings.py:


INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'hello.TomAndJerry',  # Add this line to conf the App we create just now
)

Em,now we need A Templates Directory to hold our templates, in the project directory create a folder named templates,and create a html file -- TomAndJerry.html the code looks this:


<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <title>Tom And Jerry</title>
        <style type="text/css" media="screen">
            h1 {
                color: gray;   
            }
            p {
                font-size: 14px;
            }
            ul {
                list-style:none;
            }
        </style>
    </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 tom_is_power %}
            <p>
                Tom win the game!
            </p>
        {% else %}
            <p>
                Jerry win the game!
            </p>
        {% endif %}
    </body>
</html>


And then,we have to tell the settings.py: we make a templates, when I want it, you have to give me work it out! Don't forget to use absolute paths, not relative paths.


TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    "/home/zoo/hello/templates",
)

When you look at the html code which is a bit different from the html we ever seen before,we got the double quotes and the code if the {% %}, that is the dynamic variables we will pass to the template file in the views.py file.In this way, the content we generated will currently passed to the template.

Add, you may want to know, why we don't make the Css Style out,and link it from a external file like style.css.That is we should conf it later,don't be worry, I won't forget it.

For now,we can create our functions in the App views.py:



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

from django.shortcuts import render_to_response

def show(request):
    title = "The roles in the show:"
    players = ["Tom","Jerry","Fat dog"]
    tom_is_power = True
    return render_to_response("TomAndJerry.html", locals())

Well,don't forget the url we going to conf:


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

urlpatterns = patterns('',
    (r'^$', show),  # conf the function
)

Now, we almost done about the basic page. Just check out the job,just start the server:


zoo@ubuntu:~/Desktop$ python manage.py runserver 0.0.0.0:8000

Good!It works!Haha...but for the code, I use a hack to save time, the locals() function is all the vars in the context(includes the request). Just try it:


zoo@ubuntu:~/桌面/T3$ python
Python 2.6.5 (r265:79063, Oct  1 2012, 22:07:21) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> locals()
{'__builtins__': , '__name__': '__main__', '__doc__': None, '__package__': None}
>>> 

So, that is our basic things about the Templates System.Now,we can do something fun to see Tom and Jerry who is win by the two numbers generated by the computer using rand() function.If the number are the same,no one win,else Tom win(Tom always win) Nothing new,just for fun.

Change the template html file:


<html>
    <head>
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <title>Tom And Jerry</title>
        <style type="text/css" media="screen">
            h1 {
                color: gray;   
            }
            p {
                font-size: 14px;
            }
            ul {
                list-style:none;
            }
        </style>
    </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>
        {% else %}
            <p>
                Tom Win the game!
            </p>
        {% endif %}
    </body>
</html>

Also, change the views.py to re-create the function:


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

from django.shortcuts import render_to_response
import random

def show(request):
    title = "The roles in the show:"
    players = ["Tom","Jerry","Fat dog"]
    tom_number = int(random.random()*10)
    jerry_number = int(random.random()*10)
    if tom_number == jerry_number:
        same = True
    else:
        same = False
    return render_to_response("TomAndJerry.html", locals())

Now,we can refresh the page and see the different page.Yoo! The cat will never win,poor cat...LOL...

But,there are something more about the template system, you can learn it by the django-doc.The next post we will learn the Model of the Django which is the core concept of the MVT(model,view,template). You won't want to miss!

没有评论:

发表评论