七日Python之路--第五天(之Django官方文档)

时间:2022-07-22
本文章向大家介绍七日Python之路--第五天(之Django官方文档) ,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

(一)关于数据库

之前一直使用Django自带的SQLite3数据库,感觉挺爽的,啥都不用管。但是,学习岂能贪图便利。遂开始使用MyQL。但是似乎不太顺利。首先在新建的项目mysite下,修改 settings.py 根配置文件。

dizzy@dizzy-pc:~/Python/django_project/mysite$ vim mysite/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django', #数据库需要提前建好
        'USER':'root',
        'PASSWORD':'944898186',
        'HOST':'localhost',
        'PORT':'3306',
    }
}

LANGUAGE_CODE = 'zh-cn'
TIME_ZONE = 'Asia/Shanghai'

#然后执行
>>> python manage.py syncdb

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

其实这样一般还会出现问题的。会提示找不到MySQLdb的。解决办法就是安装 MySql-python。下面摘自网络:

1. sudo easy_install mysql-python
    若报错,提示找不到setuptools
    需要先安装setuptools
2. sudo apt-get install python-setuptools
    继续执行 1
    若提示EnvironmentError: mysql_config not found(即找不到mysql_config)原因没有安装libmysqlclient
3. 在/etc/apt/sources.list 中加入 deb http://security.ubuntu.com/ubuntu maverick-security main
4. sudo apt-get install libmysqlclient-dev
    仍然失败,提示找不到Python.h
5. 在/etc/apt/sources.list 中加入 deb http://ubuntu.mirror.cambrium.nl/ubuntu/ maverick main
6. 执行 sudo apt-get install python-dev
    重新执行1 ,mysql-python安装成功

此时,再执行以下命令。便可以创建数据库表

dizzy@dizzy-pc:~/Python/django_project/mysite$ ./manage.py syncdb
#若使用 ./*.py 需要给 *.py 可执行权限,使用: chmod a+x *.py 给所有用户添加权限
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session

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): y
Please enter either "yes" or "no": yes
Username (leave blank to use 'dizzy'): 
Email address: lpe234@qq.com
Password: 
Password (again): 
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)

至此。所有的东西跟以前一样了。刚才还吧 SQLite3装上了,有时间的话研究下....

下面继续官方文档。


(二)编写你的第一个 Django 程序

由于之前的 初试Django 就是按这个例子来的。so..下面的内容会出略一些

(1)创建app应用 polls。

dizzy@dizzy-pc:~/Python/django_project/mysite$ ./manage.py startapp polls
dizzy@dizzy-pc:~/Python/django_project/mysite$ ls polls
admin.py  __init__.py  models.py  tests.py  views.py

(2)创建model

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):
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    poll = models.ForeignKey(Poll)
    def __unicode__(self):
        return self.choice_text

在setting .py 全局配置文件中添加INSTALLED__APP,然后查看创建polls.models的SQL语句,并创建数据库表

dizzy@dizzy-pc:~/Python/django_project/mysite$ ./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,
    `choice_text` varchar(200) NOT NULL,
    `votes` integer NOT NULL,
    `poll_id` integer NOT NULL
)
;
ALTER TABLE `polls_choice` ADD CONSTRAINT `poll_id_refs_id_3aa09835` FOREIGN KEY (`poll_id`) REFERENCES `polls_poll` (`id`);

COMMIT;

#其中外键等的创建,是和数据库有关的。正是MySQLdb的引入......

dizzy@dizzy-pc:~/Python/django_project/mysite$ ./manage.py syncdb

--2014年07月25日18:17:46


明天周末,感觉好想休息一下啊。哈哈。刚才彻底的处理了一下输入法的问题,安装上搜狗输入法,瞬间感觉效率好高啊。这提升,简直不是一个档次!!!

搜狗Ubuntu输入法地址:http://pinyin.sogou.com/linux/?r=pinyin

具体的方法网上搜索一下吧。使用fcitx输入法系统,在系统设置-语言支持界面设置。然后log out即可。

感觉实在好爽啊!比以前的谷歌输入法不知好了多少。猜测可能是由于在Win下一直使用sougou输入法的原因。

好了,闲话有些多。继续Django官方文档之旅。

--2014年07月25日23:27:06


(3)完善models.py

from django.db import models

# Create your models here.

from django.utils import timezone

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
        return self.question
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

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

(4)要想在admin中管理,新创建的model,需要在admin.py 中进行注册。

from django.contrib import admin

# Register your models here.

from models import Poll

admin.site.register(Poll)

(5)对models在admin界面上的布局进行重构。

#需要使用到 admin.ModelAdmin 类,使PollAdmin 从其继承而来。

from django.contrib import admin
from polls.models import Poll

class PollAdmin(admin.ModelAdmin):
    fields = ['pub_date','question']
admin.site.register(Poll,PollAdmin)

继续重构

#在admin模块中,可以进行分panel面板来显示同一app中的不同model

#coding=utf-8

from django.contrib import admin

# Register your models here.

from models import Poll,Choice

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
                    ('问题',{'fields':['question','pub_date']}),
                    #('时间',{'fields':['pub_date'],'classes':['collapse']})
                ]

admin.site.register(Poll,PollAdmin)

#在fieldsets中,[]列出所有的panel列表,其中()是每个panel的详细配置。
  #其中第一个参数是panel的标题,第二个是字典类型的详细字段。{'fields':['','','']}
#可以设置panel是否可以折叠,设置'classes'属性的值为'collapse'

对于与Poll有关联的Choice,可以直接注册Choice到admin 即可。

但是这种效率不高。可以使用 admin.StackedInline

#coding=utf-8

from django.contrib import admin

# Register your models here.

from models import Poll,Choice

class ChoiceInline(admin.StackedInline):
    model = Choice
    extra = 2

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
                    ('问题',{'fields':['question']}),
                    ('时间',{'fields':['pub_date'],'classes':['collapse']})
                ]
    inlines = [ChoiceInline]

admin.site.register(Poll,PollAdmin

#对于外键的引入,使用admin.StackedInline,然后在相应的model admin重构中,加入列表或元组形式的inlies
#extra = 3 可以控制显示个数,默认为3个
#还可以使用 admin.Tabular 来横向条状以表格形式显示数据

继续修改polls中的admin.py,但是遇到一些问题。

注:在模型models中的某个Model下,新建一个有返回值的函数。官方文档显示是可以在admin相应列表项中显示。但是自己在测试的时候,却不能显示。报错信息:

PollAdmin.list_display[2], 'was_published_recently' is not a callable or an attribute of 'PollAdmin' or found in the model 'Poll'.
#coding=utf-8

from django.contrib import admin

# Register your models here.

from models import Poll,Choice

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 2

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
                    ('问题',{'fields':['question']}),
                    ('时间',{'fields':['pub_date'],'classes':['collapse']})
                ]
    inlines = [ChoiceInline]
    #list_display = ('question','pub_date','was_published_recently')
    list_display = ('question','pub_date')

admin.site.register(Poll,PollAdmin)

在settings中,设置默认模板位置。


O(∩_∩)O哈哈~,由于更换输入法的缘故。不觉发现谷歌拼音输入法的一个BUG。模(mu)板在谷歌输入法在被设置成了模(mo)板。


编写views并配置urls。

#polls/views.py

from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse

def index(request):
    return HttpResponse("hello world!")
#polls/urls.py

from django.conf.urls import patterns,url

import views

urlpatterns = patterns('',
    url(r'^$',views.index,name='index'),
)
#mysite/urls.py

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^poll/',include('polls.urls')),
)

由于之前看过,现在再看一遍有些烦躁。╮(╯▽╰)╭................

算了搞点有意思的东西吧。先暂停一下。自从有了搜狗,这日期打的真爽,O(∩_∩)O哈!

--2014年07月26日02:42:04