2013年9月24日星期二

Crusher Django Tutorial(4) Using Basic Model

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 Template System in Django. And that is just for the static page,at least the data we pass from views.py is in the memory of the computer,not in the database, that means when we shut down the server or we shut down the computer,the data gone.If we use the database, we can store it in the local disk, that can be used when we load it,but not re-create it from the memory. In order to create the "temporary" permanent data(nothing is permanent...), we need to play with Model in Django.So let's move on!

With Django, we can use many database products,like Mysql,Sqlite,Oracle,but we will use the smallest DB -- Sqlite3 to learn the Model.In fact,in the small case of webpage, we don't need to use the strong DB like Oracle even Mysql.We have ORM, right? I think the ORM is great, because I am an idiot for SQL...

So,before we create the models today, we should do something to conf the database,include the: name of database(sqlite3), the local file(a file ends with ".db"),we don't need other info using the sqlite3, if you use other database you should fill the fields in the following code in the settings.py(remember her?):


DATABASE_ENGINE = ''
DATABASE_NAME = ''
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''

Well, I will continue the previous post -- TomAndJerry Show App, and if you miss it, you can just read it back.Besides, we will use the url conf so that we can make it all we have learned used in our App.First, we conf the databse:

After conf the database, we should create the role model in our App-- TomAndJerry, in the class -- Player we give every role has three fields: name,age,role in the Cartoon. Edit the models.py in the folder TomAndJerry like this:

 
DATABASE_ENGINE = 'sqlite3'           
DATABASE_NAME = './data.db'            
DATABASE_USER = ''             
DATABASE_PASSWORD = ''         
DATABASE_HOST = ''              
DATABASE_PORT = ''
 

That is our conf about the database we used.Just give the name and the local file of the database.

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

from django.db import models

class player(models.Model):
    name = models.CharField(max_length = 30)
    age = models.IntegerField()
    role = models.CharField(max_length = 40)
    
    # re-define the unicode function
    def __unicode__(self):
        return u'%s is a(an) %s,he is %s years old' % (self.name,self.role,self.age)
    
    class Meta:
        ordering = ['age']
 

So,we have created our player class, the __unicode__() is the way we show an object of the player class, the Meta class is a Meta Class which inclueds the ording rule -- age.

After created the player model,we need to see the real SQL code and check it if anything wrong in it, just using the command python manage.py sqlall TomAndJerry and python manage.py validate:

 
zoo@ubuntu:~/hello$ python manage.py sqlall TomAndJerry
BEGIN;
CREATE TABLE "TomAndJerry_player" (
    "id" integer NOT NULL PRIMARY KEY,
    "name" varchar(30) NOT NULL,
    "age" integer NOT NULL,
    "role" varchar(40) NOT NULL
)
;
COMMIT;
 
 
zoo@ubuntu:~/hello$ python manage.py validate
0 errors found
 

We see that it will give the SQL code for our model.Now, we need to install it to our App,that means create the Table in the SQL code:

 
zoo@ubuntu:~/hello$ python manage.py validate
0 errors found
zoo@ubuntu:~/hello$ python manage.py syncdb
Creating table auth_permission
Creating table auth_group
Creating table auth_user
Creating table auth_message
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table TomAndJerry_player

You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes
Username (Leave blank to use 'zoo'): zoo
E-mail address: aswe@gmail.com
Password: 
Password (again): 
Superuser created successfully.
Installing index for auth.Permission model
Installing index for auth.Message model
 

In this step,we see that the table TomAndJerry_player has been created,besides, we also created a admin user(That's the next post will talked about) for our website just do as Django tell us is ok.If everything is ok,we will see a local database data.db has been created which means our job is ok for now.

Now,we have the database and the table,but there is nothing in it.So we have to insert something into table.Just using the python manage.py shell in the website root folder.

 
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.
(InteractiveConsole)
>>> from TomAndJerry.models import player       # import the class
>>> Tom = player(name="Tom",age=5,role="mouse") # create a object but not insert into table
>>> Tom                                         # show it
 
>>> Tom.save()                                  # save means insert into tabel
>>> player.objects.all()                        # get all data
[]
>>> Jerry = player(name="Jerry",age=6,role="cat")
>>> Jerry

>>> player.objects.all()                        # before save Jerry
[]
>>> Jerry.save()                                # saved Jerry
>>> player.objects.all()
[, ]
>>> from sys import exit
>>> exit(0)
 

Now,we get two roles in our table player. The next job is show them in our page.For easy way, we just create another template named show.html in the folder templates.

 
<html>
<head>
 <title>Show The Players</title>
</head>
<body>
 <h1>The Cartoon Show</h1>
 <h2>The role in the Cartoon:</h2>
 <ol>
  {% for role in roles %}
   <li>{{ role }}</li>
  {% endfor %}
 </ol>
</body>
</html>
 

The tempalte html has nothing new for now. But we have to create a new function named just_show() in the views.py:

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

from django.shortcuts import render_to_response
from hello.TomAndJerry.models import player   # don't forget import the class

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())

def just_show(request):
    roles = player.objects.all()
    return render_to_response("show.html", locals())
 

And we need to conf the urls.py(Oh, so much work to do and so few time...)

 
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
    (r'^just_show/$', just_show),
)
 

Now, we can just test our job:

Yoo,it works.So,that is just what we have learn today.But we can put the all things we have learn.Extends the url to show the everyone's info.If we input Tom,we show Tom's info, we input Jerry, we show Jerry's info,we input a name not in our database, we raise 404 error,ok,just start it.

Create html file named info.html as this:

 
<html>
<head>
 <title>Info For Player</title>
</head>
<body>
 {% if role %}
  <h1>{{ role.name }} is A(an) {{ role.role }}, and he is {{ role.age }} years old.</h1>
 {% else %}
  <h1>Error</h1>
 {% endif %}
</body>
</html>
 

And then we create a function in views.py named info:

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

from django.http import Http404, HttpResponse
from django.shortcuts import render_to_response
from hello.TomAndJerry.models import player   # don't forget import the class

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())

def just_show(request):
    roles = player.objects.all()
    return render_to_response("show.html", locals())


def info(request,name = None):
    if name is None:  # Nothing input return the error info
        return HttpResponse("nothing input")
    try:
        role = player.objects.get(name=name)
        return render_to_response("info.html", locals())
    except Exception:
        raise Http404()
 

And don't forget the urls.py:

 
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
    (r'^just_show/$', just_show),
    (r'^info/(.+)/', info),
    (r'^info/$', info),
)
 

Now,we test our job we did:

Great! Everything is ok. Well, you may think that when we input the things into the table using the command line is too silly.That's ture,we will learn the how to use admin page next post.Don't miss it and welcome feedback~!

没有评论:

发表评论