标签:django;admin
一、前言:
在创建完Django项目后,每个app下,都会有一个urls.py文件,里边会有如下几行:
from django.contrib import admin
urlpatterns = [
url(r‘^admin/‘,admin.site.urls),
]
上边看到导入的admin模块
二、主要功能:
功能1:提供数据库管理功能
基于admin模块,可以实现类似数据库客户端的功能,对数据进行增删改查
功能2:二次开发
基于该模块的数据管理功能,可以二次定制一些实用的功能。
三、使用方法:
1、步骤1:在settings.py中,INSTALLED_APPS中,加入django.contrib.admin(默认情况已经有。)
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘app01‘, #自己的应用 ]
2、步骤2:urls.py创建admin路由(默认情况已经有)
urlpatterns = [ url(r‘^admin/‘,admin.site.urls), ...... ]
3、步骤3:在settings.py配置文件中,中间件注册(默认情况已经有)
MIDDLEWARE_CLASSES = [ ‘django.middleware.security.SecurityMiddleware‘, ‘django.contrib.sessions.middleware.SessionMiddleware‘, ‘django.middleware.common.CommonMiddleware‘, #‘django.middleware.csrf.CsrfViewMiddleware‘, ‘django.contrib.auth.middleware.AuthenticationMiddleware‘, ‘django.contrib.auth.middleware.SessionAuthenticationMiddleware‘, ‘django.contrib.messages.middleware.MessageMiddleware‘, ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘, ]
4、步骤4:创建admin管理用户
python3 manage.py createsuperuser [root@Centos7-33 test1]# python3 manage.pycreatesuperuser Username (leave blank to use ‘root‘):sunday Email address: sunday@itour.cc Password: Password (again): The password is too similar to the emailaddress. Password: Password (again): Superuser created successfully.
5、步骤5:在app 的models.py文件中创建表信息,即表类
from django.db import models from time import strftime class userinfo(models.Model): gender_choices = ( (0, "男"), (1, "女"), ) nid = models.AutoField(primary_key=True) name = models.CharField(max_length=30, verbose_name=‘用户名‘) email = models.EmailField(db_index=True,verbose_name=‘邮箱地址‘) memo = models.TextField(verbose_name=‘备注‘) img = models.ImageField(upload_to=strftime(‘%Y%m%d‘),verbose_name=‘图片路径‘) user_type = models.ForeignKey("UserType", null=True, blank=True) gender = models.IntegerField(choices=gender_choices,default=0) def __str__(self): return self.name class UserType(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name
6、步骤6:在app的 admin.py中注册表
from django.contrib import admin # Register yourmodels here. from .models import userinfo,UserType admin.site.register(userinfo) admin.site.register(UserType)
7、步骤7:生成表结构
python3 manage.py makemigrations python3 manage.py makemigrations app01 #app01为项目应用名称 python3 manage.py migrate #同步数据库
注意:在数据库表结构发生变动时,再次执行python manage.py makemigrations就会报错,这是因为此时表中可能已经有数据,貌然变动表结构会有影响,此时的解决方法有两种,一种是,设置新增字段的default=‘xxx‘某个值,但是这种通用性不是很好。另外一种是,设置该字段null=True。即允许为空即可
8、步骤8:运行项目,登陆管理界面
python3 manage.py runserver 0.0.0.0:8000
访问URL:http://IP:8000/admin
四、最终展示页面
本文出自 “都市布衣” 博客,请务必保留此出处http://sunday208.blog.51cto.com/377871/1890532
标签:django;admin
原文地址:http://sunday208.blog.51cto.com/377871/1890532