Django之模型注册
接着上一篇:Django之创建项目
目的:一个空项目创建好了,我们在models.py中新增3张表并在admin界面中显示,并能操作它们。
示例models
编辑models.py
# -*- coding:utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Blog(models.Model): name = models.CharField(max_length=100,verbose_name=u"博文名称") tagline = models.TextField(verbose_name=u"标注") def __unicode__(self): return self.name class Meta: verbose_name = "博客主题" verbose_name_plural = "博客主题" class Author(models.Model): name = models.CharField(max_length=50,verbose_name=u"姓名") email = models.EmailField(verbose_name=u"邮箱") class Meta: verbose_name = "作者" verbose_name_plural = "作者" class Entry(models.Model): blog = models.ForeignKey(Blog) headling = models.CharField(max_length=255,verbose_name=u"标头") body_text = models.TextField(verbose_name=u"博体") pub_date = models.DateField(verbose_name=u"发布日期") mod_date = models.DateField(verbose_name=u"修改日期") authors = models.ManyToManyField(Author) n_comments = models.IntegerField(verbose_name=u"备注") n_pingbacks = models.IntegerField() rating = models.IntegerField() def __unicode__(self): return self.headling class Meta: verbose_name = "博文" verbose_name_plural = "博文"
模型注册到admin
from django.contrib import admin # Register your models here. from sqlOper import models class AuthorAdmin(admin.ModelAdmin): list_display = ('name','email') class BlogAdmin(admin.ModelAdmin): list_display = ('name','tagline') class EntryAdmin(admin.ModelAdmin): list_display = ('headling','pub_date','mod_date','n_comments') # admin.site.register([models.Blog,models.Author,models.Entry]) admin.site.register(models.Blog,BlogAdmin) admin.site.register(models.Author,AuthorAdmin) admin.site.register(models.Entry,EntryAdmin)
将表实例化到数据库
>python manage.py makemigrations Migrations for 'sqlOper': sqlOper\migrations\0001_initial.py: - Create model Author - Create model Blog - Create model Entry >python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, sqlOper Running migrations: Applying sqlOper.0001_initial... OK
创建超级用户
D:\py\python\spiders\django\djangoStudy>python manage.py createsuperuser Username (leave blank to use 'administrator'): admin Email address: 2905@qq.com Password: Password (again): Superuser created successfully.
登陆界面,输入超级用户名/密码
现在可以对你的表进行操作了,添加一些作者、博客,内容信息吧。
关于中文的问题
1、django-admin界面显示中文
修改settings.py
LANGUAGE_CODE = 'zh_Hans'
TIME_ZONE = 'Asia/Shanghai'
最新的django版本(1.9)中只有zh_Hans,可以将其复制为zh_CN
2、admin中新建表显示中文
使用django中的原类Meta
选项参考:http://kaozjlin.iteye.com/blog/1662617