Django项目 实例 日记

参考资料:

Django documentation

Django 基础教程

涉及的python包:

django,jieba,MySqldb,json,re,urllib2/scrapy,datetime


1.创建

C:\python\Django>django-admin startproject strip

C:\python\Django>cd strip

C:\python\Django\strip>tree /f
卷 Windows8_OS 的文件夹 PATH 列表
卷序列号为 00000090 EA34:912D
C:.
│  manage.py
│
└─strip
        settings.py
        urls.py
        wsgi.py
        __init__.py



2.生成app

C:\python\Django\strip>python manage.py startapp author

C:\python\Django\strip>python manage.py startapp spot

C:\python\Django\strip>python manage.py startapp spot

C:.
│  manage.py
│
├─author
│  │  admin.py
│  │  models.py
│  │  tests.py
│  │  views.py
│  │  __init__.py
│  │
│  └─migrations
│          __init__.py
│
├─spot
│  │  admin.py
│  │  models.py
│  │  tests.py
│  │  views.py
│  │  __init__.py
│  │
│  └─migrations
│          __init__.py
│
└─strip
        settings.py
        settings.pyc
        urls.py
        wsgi.py
        __init__.py
        __init__.pyc

3.在settings中添加app

1.修改strip/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'author',
    'spot',
)

2.检查与数据库的链接

C:\python\Django\strip>python manage.py shell

In [2]: from django.db import connection as conn

In [3]: print conn


4.分析网站中应该创建的对象实例,表。

5.添加数据库信息

修改strip/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'smartrip',
        'USER':'root',
        'PASSWORD':'root',
        'HOST':'',
        'PORT':'',
    }
}

6.编写app的models

author/mdoels.py

from django.db import models
from django.utils import timezone

# Create your models here.
class user(models.Model):
	email = models.EmailField(default='')
	username = models.CharField(max_length=40,unique=True)
	pword = models.CharField(max_length=20)
	cdate = models.DateField(default=timezone.now)
	birth = models.DateField(default=timezone.now)
	mysite = models.URLField(default='')
	sex = models.IntegerField(default=0)
	intro = models.TextField(default='')
	def __unicode__(self):
		return self.username



spot/models.py

from django.db import models
from django.utils import timezone
from author.models import user

# Create your models here.

class spot(models.Model):
	spotname = models.TextField(default='')
	address = models.CharField(max_length=100)
	want_it = models.IntegerField(default=0)
	description = models.TextField(default='')
	style = models.CharField(default='',max_length=12)
	cover = models.TextField(default='')
	visited = models.IntegerField(default=0)

	def __unicode__(self):
		return self.spotname

class photo(models.Model):
	photo_url = models.TextField(default='')
	pdate = models.DateField(default=timezone.now)
	ptext = models.TextField(default='')
	article_title = models.TextField(default='')
	article_link = models.TextField(default='')
	like_it = models.IntegerField(default=0)
	spot = models.ForeignKey(spot,null=True,blank=True)
	keyWords = models.TextField(default='')

	def __unicode__(self):
		return photo_url

class article(models.Model):
	mileage = models.FloatField(default=0)
	day_count = models.CharField(max_length=5,null=True)
	click = models.IntegerField(default=0)
	visited = models.IntegerField(default=0)
	routes = models.TextField(default='')
	want_it = models.IntegerField(default=0)
	coverpic = models.TextField(default='')
	user = models.ForeignKey(user,null=True,blank=True)
	spots = models.ManyToManyField(spot,blank=True)
	photos = models.ManyToManyField(photo,blank=True)
	
	
	def __unicode__(self):
		return self.article_title
	




7.生成models

1.形成变更

C:\python\Django\strip>python manage.py makemigrations
System check identified some issues:

WARNINGS:
spot.article.photos: (fields.W340) null has no effect on ManyToManyField.
spot.article.spots: (fields.W340) null has no effect on ManyToManyField.
Migrations for 'spot':
  0001_initial.py:
    - Create model article
    - Create model photo
    - Create model spot
    - Add field spot to photo
    - Add field photos to article
    - Add field spots to article
    - Add field user to article
Migrations for 'author':
  0001_initial.py:
    - Create model user

2.查看变更的sql语句

C:\python\Django\strip>python manage.py sqlmigrate author 0001
BEGIN;
CREATE TABLE `author_user` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `email` varchar(254) NOT NULL, `username` varchar(40) NOT NULL UNIQUE, `pword` varchar(20) NOT NULL, `cdate` date NOT NULL, `birth` date NOT NULL, `mysite` varchar(200) NOT NULL, `sex` integer NOT NULL, `intro` longtext NOT NULL);

COMMIT;

C:\python\Django\strip>python manage.py sqlmigrate spot 0001
BEGIN;
CREATE TABLE `spot_article` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `mileage` double precision NOT NULL, `day_count` varchar(5) NULL, `click` integer NOT NULL, `visited` integer NOT NULL, `routes` longtext NOT NULL, `want_it` integer NOT NULL, `coverpic` longtext NOT NULL);
CREATE TABLE `spot_photo` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `photo_url` longtext NOT NULL, `pdate` date NOT NULL, `ptext` longtext NOT NULL, `article_title` longtext NOT NULL, `article_link` longtext NOT NULL, `like_it` integer NOT NULL, `keyWords` longtext NOT NULL);
CREATE TABLE `spot_spot` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `spotname` longtext NOT NULL, `address` varchar(100) NOT NULL, `want_it` integer NOT NULL, `description` longtext NOT NULL, `style` varchar(12) NOT NULL, `cover` longtext NOT NULL, `visited` integer NOT NULL);
ALTER TABLE `spot_photo` ADD COLUMN `spot_id` integer NULL;
ALTER TABLE `spot_photo` ALTER COLUMN `spot_id` DROP DEFAULT;
CREATE TABLE `spot_article_photos` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `article_id` integer NOT NULL, `photo_id` integer NOT NULL, UNIQUE (`article_id`, `photo_id`));
CREATE TABLE `spot_article_spots` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `article_id` integer NOT NULL, `spot_id` integer NOT NULL, UNIQUE (`article_id`, `spot_id`));
ALTER TABLE `spot_article` ADD COLUMN `user_id` integer NULL;
ALTER TABLE `spot_article` ALTER COLUMN `user_id` DROP DEFAULT;
CREATE INDEX `spot_photo_e72b53d4` ON `spot_photo` (`spot_id`);
ALTER TABLE `spot_photo` ADD CONSTRAINT `spot_photo_spot_id_281298f_fk_spot_spot_id` FOREIGN KEY (`spot_id`) REFERENCES `spot_spot` (`id`);
ALTER TABLE `spot_article_photos` ADD CONSTRAINT `spot_article_photos_article_id_18e821d_fk_spot_article_id` FOREIGN KEY (`article_id`) REFERENCES `spot_article` (`id`);
ALTER TABLE `spot_article_photos` ADD CONSTRAINT `spot_article_photos_photo_id_51ee98db_fk_spot_photo_id` FOREIGN KEY (`photo_id`) REFERENCES `spot_photo` (`id`);
CREATE INDEX `spot_article_photos_a00c1b00` ON `spot_article_photos` (`article_id`);
CREATE INDEX `spot_article_photos_b4e75e23` ON `spot_article_photos` (`photo_id`);
ALTER TABLE `spot_article_spots` ADD CONSTRAINT `spot_article_spots_article_id_7c4e22bc_fk_spot_article_id` FOREIGN KEY (`article_id`) REFERENCES `spot_article` (`id`);
ALTER TABLE `spot_article_spots` ADD CONSTRAINT `spot_article_spots_spot_id_723f7c87_fk_spot_spot_id` FOREIGN KEY (`spot_id`) REFERENCES `spot_spot` (`id`);
CREATE INDEX `spot_article_spots_a00c1b00` ON `spot_article_spots` (`article_id`);
CREATE INDEX `spot_article_spots_e72b53d4` ON `spot_article_spots` (`spot_id`);
CREATE INDEX `spot_article_e8701ad4` ON `spot_article` (`user_id`);
ALTER TABLE `spot_article` ADD CONSTRAINT `spot_article_user_id_42c7d0d8_fk_author_user_id` FOREIGN KEY (`user_id`) REFERENCES `author_user` (`id`);

COMMIT;

3.生成这些变更

C:\python\Django\strip>python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, messages
  Apply all migrations: sessions, admin, author, spot, auth, contenttypes
Synchronizing apps without migrations:
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying author.0001_initial... OK
  Applying sessions.0001_initial... OK
  Applying spot.0001_initial... OK

4.查看mysql

C:\python\Django\strip>mysql -u root -p smartrip
Enter password: ****

mysql> show tables;
+----------------------------+
| Tables_in_smartrip         |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| author_user                |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
| spot_article               |
| spot_article_photos        |
| spot_article_spots         |
| spot_photo                 |
| spot_spot                  |
+----------------------------+
16 rows in set (0.00 sec)

auth 前缀的表示django为admin自动生成的superuser表

django 前缀的表包含了变更models的历史

app名称为前缀的表就是models.py中代码的映射。

其中多对多关系ManyToManyField将被自动的映射为一张包含两种id对应信息的表

 

mysql> desc  spot_article_photos;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| id         | int(11) | NO   | PRI | NULL    | auto_increment |
| article_id | int(11) | NO   | MUL | NULL    |                |
| photo_id   | int(11) | NO   | MUL | NULL    |                |
+------------+---------+------+-----+---------+----------------+
3 rows in set (0.02 sec)

mysql> desc spot_photo;
+---------------+----------+------+-----+---------+----------------+
| Field         | Type     | Null | Key | Default | Extra          |
+---------------+----------+------+-----+---------+----------------+
| id            | int(11)  | NO   | PRI | NULL    | auto_increment |
| photo_url     | longtext | NO   |     | NULL    |                |
| pdate         | date     | NO   |     | NULL    |                |
| ptext         | longtext | NO   |     | NULL    |                |
| article_title | longtext | NO   |     | NULL    |                |
| article_link  | longtext | NO   |     | NULL    |                |
| like_it       | int(11)  | NO   |     | NULL    |                |
| keyWords      | longtext | NO   |     | NULL    |                |
| spot_id       | int(11)  | YES  | MUL | NULL    |                |
+---------------+----------+------+-----+---------+----------------+
9 rows in set (0.02 sec)

mysql> desc spot_article;
+-----------+------------+------+-----+---------+----------------+
| Field     | Type       | Null | Key | Default | Extra          |
+-----------+------------+------+-----+---------+----------------+
| id        | int(11)    | NO   | PRI | NULL    | auto_increment |
| mileage   | double     | NO   |     | NULL    |                |
| day_count | varchar(5) | YES  |     | NULL    |                |
| click     | int(11)    | NO   |     | NULL    |                |
| visited   | int(11)    | NO   |     | NULL    |                |
| routes    | longtext   | NO   |     | NULL    |                |
| want_it   | int(11)    | NO   |     | NULL    |                |
| coverpic  | longtext   | NO   |     | NULL    |                |
| user_id   | int(11)    | YES  | MUL | NULL    |                |
+-----------+------------+------+-----+---------+----------------+
9 rows in set (0.04 sec)

5.利用django的QuerySet API编写注入数据库的脚本

1.先用shell来查看models的类的结构

其余的不给出了

6.完善表之间的m2m关系:

#coding:utf-8


import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "strip.settings")

import django
if django.VERSION >= (1, 7):#自动判断版本
    django.setup()

import json

import jieba

from author.models import *
from spot.models import *


for a in article.objects.all():
    for p in photo.objects.filter(article_url=a.article_url):
        a.photos.add(p)

for a in article.objects.all():
    s = ''
    for k in a.photos.values('keyWords'):
        s+=','.join(json.loads(k.values()[0]))

    for p in spot.objects.all():
        for w in jieba.cut(p.spotname,cut_all=True):
            if w in s:
                a.spots.add(p)

7.创建superuser 管理admin站点

C:\python\Django\strip>python manage.py createsuperuser
Username (leave blank to use 'zhiziyun'): wdd1
Email address: [email protected]
Password:
Password (again):
Superuser created successfully.

8.添加models到admin中:

app/admin:

from django.contrib import admin

# Register your models here.
from models import 	spot,photo,article


class spotadmin(admin.ModelAdmin):
	list_display = ('spotname','address','want_it')
	# filter_horizontal = ('articles',)

class articleadmin(admin.ModelAdmin):
	list_display = ('article_title','user','want_it','routes')
	# filter_horizontal = ('photos','trip_days')

class photoadmin(admin.ModelAdmin):
	list_display = ('article_title','id','keyWords')

admin.site.register(spot,spotadmin)
admin.site.register(article,articleadmin)
admin.site.register(photo,photoadmin)


9.打开admin页面:

C:\python\Django\strip>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
August 24, 2015 - 15:53:58
Django version 1.8, using settings 'strip.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Django项目 实例 日记_第1张图片

默认是英文环境,在strip/settings 设置语言环境:

LANGUAGE_CODE = 'zh-hans'

Django项目 实例 日记_第2张图片

Django项目 实例 日记_第3张图片



Django项目 实例 日记_第4张图片



Django项目 实例 日记_第5张图片



Django项目 实例 日记_第6张图片


这是第一次看到除了代码以为的彩色页面,是不是有点小激动?呵呵,在以后的后台管理中仍然离不开它。它作为一个工具。结合QuerySet是的Django网站的后台管理变得特别的方便。

今天就到这里。

2015-08-24 16:09:56

你可能感兴趣的:(python)