Ubuntu12.04系统上写你的第一个Django1.5应用(一)-环境搭建-数据库,时区,语言,配置

Ubuntu12.04系统下写你的第一个Django1.5应用(一)--环境搭建--数据库,时区,语言,配置


系统:Ubuntu12.04

Django 版本:1.5


确定环境已经搭建好,命令行中输入:

jiangge@ubuntu:~$ python -c "import django; print(django.get_version())"
1.5


1.5是Django的版本,本文基于1.5写成.



创建一个项目: 在命令行输入:

jiangge@ubuntu:~$ django-admin.py startproject mysite

此命令创建一个一个Django项目,tree一下mysite目录,可以看到:

jiangge@ubuntu:~$ tree mysite
mysite
├── manage.py
└── mysite
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

1 directory, 5 files



启动开发者服务器:

切换到外面的mysite目录(Change into the outer mysite directory),然后在命令行输入:

jiangge@ubuntu:~$ cd mysite
jiangge@ubuntu:~/mysite$ python manage.py runserver

会看到命令行有如下信息,则表示启动成功:

Validating models...

0 errors found
March 09, 2013 - 22:48:24
Django version 1.5, using settings 'mysite.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.


在浏览器中输入:

http://127.0.0.1:8000/


数据库配置:

编辑mysite目录下的settings.py文件

jiangge@ubuntu:~/mysite$ vim mysite/settings.py

填写数据库引荐,数据库名,用户名,密码,主机,端口号:

默认已经创建数据库:

mysql>CREATE DATABASE mysite DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;



 12 DATABASES = {                                                                  
 13     'default': {                                                               
 14         'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
 15         'NAME': 'mysite',          #mysql> CREATE DATABASE mysite DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;                                                                        
 17         'USER': 'root',                                                            
 18         'PASSWORD': '123456',                                                        
 19         'HOST': '',                      # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
 20         'PORT': '',                      # Set to empty string for default.    
 21     }                                                                          
 22 }                                                                              




设置时区和语言:

编辑mysite目录下的settings.py文件

jiangge@ubuntu:~/mysite$ vim mysite/settings.py

TIME_ZONE = 'Asia/Shanghai'  #PRC
LANGUAGE_CODE = 'zh-cn'      #Simplified Chinese 


创建数据库的表结构:

jiangge@ubuntu:~/mysite$ python manage.py syncdb

命令行下会看到如下信息: 
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site

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

问,是否创建超级用户,回答'yes'

根据提示继续填写,用户名,邮箱地址,密码:

Username (leave blank to use u'jiangge'): jiangge
E-mail address: 499065469@qq.com
Password: 
Password (again): 
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)


创建App:

 命令行输入

jiangge@ubuntu:~/mysite$ python manage.py startapp polls 
此命令创建了一个polls目录,看下此目录下的文件:

jiangge@ubuntu:~/mysite$ ls
manage.py  mysite  polls
jiangge@ubuntu:~/mysite$ tree polls/
polls/
├── __init__.py
├── models.py
├── tests.py
└── views.py

0 directories, 4 files

创建模型层:

编辑polls/models.py文件,写入以下内容:

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

思考:代码中哪些对应表名?哪些对应字段名?

答案:Each model has a number of classvariables, each of which represents a database field in the model.


激活模型(Activating models) :

再次修改settings.py文件,将字符串'polls'添加到INSTALLED_APPS元组当中:

112 INSTALLED_APPS = (                                                          
113     'django.contrib.auth',                                                  
114     'django.contrib.contenttypes',                                          
115     'django.contrib.sessions',                                              
116     'django.contrib.sites',                                                 
117     'django.contrib.messages',                                              
118     'django.contrib.staticfiles',                                           
119     # Uncomment the next line to enable the admin:                          
120     # 'django.contrib.admin',                                               
121     # Uncomment the next line to enable admin documentation:                
122     # 'django.contrib.admindocs',                                           
123     'polls',                                                               
124 ) 

执行如下命令:

jiangge@ubuntu:~/mysite$ python manage.py sql polls
会看到类似以下信息:

BEGIN;
CREATE TABLE `polls_poll` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `question` varchar(200) NOT NULL,
    `pub_date` datetime NOT NULL
)
;
CREATE TABLE `polls_choice` (
    `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
    `poll_id` integer NOT NULL,
    `choice_text` varchar(200) NOT NULL,
    `votes` integer NOT NULL
)
;
ALTER TABLE `polls_choice` ADD CONSTRAINT `poll_id_refs_id_3aa09835` FOREIGN KEY (`poll_id`) REFERENCES `polls_poll` (`id`);

COMMIT; 

NOTE:The sql commanddoesn’t actually run the SQLin your database -it just prints it to the screen so that you can see what SQL Django thinksis required.

If you’re interested, also run the following commands:

  • pythonmanage.pyvalidate– Checks for any errorsin the construction of your models.
  • pythonmanage.pysqlcustompolls – Outputs anycustom SQL statements (such as table modifications orconstraints) that are defined for the application.
  • pythonmanage.pysqlclearpolls – Outputs thenecessaryDROPTABLE statements for this app, according to whichtables already exist in your database (if any).
  • pythonmanage.pysqlindexespolls – Outputs theCREATEINDEX statements for this app.
  • pythonmanage.pysqlallpolls – A combination of allthe SQL from thesql,sqlcustom, andsqlindexes commands.
再次执行syncdb:

python manage.py syncdb

NOTE: syncdb can be called as often as you like, and it will only evercreate the tables that don’t exist.


使用Django API:

命令行中输入:

python manage.py shell

NOTE:We’re using this instead of simply typing “python”, becausemanage.py sets theDJANGO_SETTINGS_MODULEenvironment variable, which gives Djangothe Python import path to yoursettings.py file.

In [3]: from polls.models import Poll, Choice 

In [4]: Poll.objects.all()
Out[4]: []

In [5]: from django.utils import timezone

In [6]: p = Poll(question="What's new?", pub_date=timezone.now())

In [7]: p.save()

In [8]: p.id
Out[8]: 1L

In [9]: p.question
Out[9]: "What's new?"

In [10]: p.pub_date
Out[10]: datetime.datetime(2013, 3, 10, 15, 2, 34, 203868, tzinfo=<UTC>)

In [11]: p.question = "What's up?"

In [12]: p.save()

In [13]: Poll.
Poll.DoesNotExist              Poll.get_previous_by_pub_date
Poll.MultipleObjectsReturned   Poll.mro
Poll.add_to_class              Poll.objects
Poll.choice_set                Poll.pk
Poll.clean                     Poll.prepare_database_save
Poll.clean_fields              Poll.save
Poll.copy_managers             Poll.save_base
Poll.date_error_message        Poll.serializable_value
Poll.delete                    Poll.unique_error_message
Poll.full_clean                Poll.validate_unique
Poll.get_next_by_pub_date      

In [13]: Poll.objects.all()
Out[13]: [<Poll: Poll object>]


polls/models.py中添加魔术方法:

from django.db import models

# Create your models here.
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    
    def __unicode__(self):
        return self.question


class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.choice_text



In [1]: from polls.models import Poll, Choice

In [2]: Poll.objects.all()
Out[2]: [<Poll: What's up?>]

In [3]: Poll.objects.filter(id=1)
Out[3]: [<Poll: What's up?>]

In [4]: Poll.objects.filter(question__startswith='What')
Out[4]: [<Poll: What's up?>]

In [5]: from django.utils import timezone

In [6]: current_year = timezone.now().year

In [7]: Poll.objects.get(pub_date__year=current_year)
Out[7]: <Poll: What's up?>

In [8]: Poll.objects.get(id=2) # Request an ID that doesn't exist, this will raise an exception.
---------------------------------------
DoesNotExist                              Traceback (most recent call last)

In [9]: Poll.objects.get(pk=1)
Out[9]: <Poll: What's up?>

In [10]: p = Poll.objects.get(pk=1) # Make sure our custom method worked.

In [11]: p.was_published_recently()
Out[11]: True

In [12]: p = Poll.objects.get(pk=1)

In [13]: p.choice_set.all()
Out[13]: []

In [14]: p.choice_set.create(choice_text='Not much', votes=0)
Out[14]: <Choice: Not much>

In [15]: p.choice_set.create(choice_text='The sky', votes=0)
Out[15]: <Choice: The sky>

In [16]: c = p.choice_set.create(choice_text='Just hacking again', votes=0)

In [17]: c.poll
Out[17]: <Poll: What's up?>

In [18]: p.choice_set.all()
Out[18]: [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

In [19]: p.choice_set.count()
Out[19]: 3

In [20]: Choice.objects.filter(poll__pub_date__year=current_year)
Out[20]: [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

In [21]: c = p.choice_set.filter(choice_text__startswith='Just hacking')

In [22]: 



mysql> desc polls_choice;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| poll_id     | int(11)      | NO   | MUL | NULL    |                |
| choice_text | varchar(200) | NO   |     | NULL    |                |
| votes       | int(11)      | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> desc polls_poll;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| question | varchar(200) | NO   |     | NULL    |                |
| pub_date | datetime     | NO   |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

mysql> 


注:本文由@易枭寒(499065469@qq.com) 根据官方文档写成.转载请注明出处和作者信息.

官方教程地址:https://docs.djangoproject.com/en/1.5/intro/tutorial01/点击打开链接