Django中的页面管理后台

Django中的页面管理后台

Djano中自带admin后台管理模块,可以通过web页面去管理,有点想php-admin,使用步骤:

  1. 在项目中models.py 中创建数据库表

     
    1. class userinfo(models.Model):

    2. nid = models.AutoField(primary_key=True)

    3. username = models.CharField(max_length=32)

    4. email = models.EmailField()

    5. ip = models.GenericIPAddressField()

    6. memo = models.TextField()

    7. img = models.ImageField()

    8. usertype=models.ForeignKey("usertype",null=True,blank=True)

    9.  
    10. class usertype(models.Model):

    11. name = models.CharField(max_length=32)

    12. def __str__(self):

    13. return self.name

  2. 在terminal中执行

     
    1. python manage.py makemigrations

    2. python manage.py migrate

    3.  
    4. #创建超级用户,设置管理员密码,密码至少8位

    5. python manage.py createsuperuser

  3. 在项目中的admin.py中设置,注册已经设置的数据库

     
    1. from django.contrib import admin

    2.  
    3. # Register your models here.

    4.  
    5. from app01 import models

    6. admin.site.register(models.userinfo)

    7. admin.site.register(models.usertype)

  4. 在页面中访问/admin,即可访问后台管理以及对数据增删改查

model详解

Django中遵循 Code Frist 的原则,即:根据代码中定义的类来自动生成数据库表。

创建表

基本结构

 
  1. from django.db import models

  2.  
  3. # Create your models here.

  4.  
  5. class userinfo(models.Model):

  6. nid = models.AutoField(primary_key=True)

  7. username = models.CharField(max_length=32)

  8. email = models.EmailField()

  9. ip = models.GenericIPAddressField()

  10. memo = models.TextField()

  11. img = models.ImageField()

  12. usertype=models.ForeignKey("usertype",null=True,blank=True)

  13.  
  14. class usertype(models.Model):

  15. name = models.CharField(max_length=32)

  16. def __str__(self):

  17. return self.name

更多字段:

 
  1. 1、models.AutoField  自增列 = int(11)

  2.   如果没有的话,默认会生成一个名称为 id 的列,如果要显示的自定义一个自增列,必须将给列设置为主键 primary_key=True。

  3. 2、models.CharField  字符串字段

  4.   必须 max_length 参数

  5. 3、models.BooleanField  布尔类型=tinyint(1)

  6.   不能为空,Blank=True

  7. 4、models.ComaSeparatedIntegerField  用逗号分割的数字=varchar

  8.   继承CharField,所以必须 max_lenght 参数

  9. 5、models.DateField  日期类型 date

  10.   对于参数,auto_now = True 则每次更新都会更新这个时间;auto_now_add 则只是第一次创建添加,之后的更新不再改变。

  11. 6、models.DateTimeField  日期类型 datetime

  12.   同DateField的参数

  13. 7、models.Decimal  十进制小数类型 = decimal

  14.   必须指定整数位max_digits和小数位decimal_places

  15. 8、models.EmailField  字符串类型(正则表达式邮箱) =varchar

  16.   对字符串进行正则表达式

  17. 9、models.FloatField  浮点类型 = double

  18. 10、models.IntegerField  整形

  19. 11、models.BigIntegerField  长整形

  20.   integer_field_ranges = {

  21.     'SmallIntegerField': (-32768, 32767),

  22.     'IntegerField': (-2147483648, 2147483647),

  23.     'BigIntegerField': (-9223372036854775808, 9223372036854775807),

  24.     'PositiveSmallIntegerField': (0, 32767),

  25.     'PositiveIntegerField': (0, 2147483647),

  26.   }

  27. 12、models.IPAddressField  字符串类型(ip4正则表达式)

  28. 13、models.GenericIPAddressField  字符串类型(ip4和ip6是可选的)

  29.   参数protocol可以是:both、ipv4、ipv6

  30.   验证时,会根据设置报错

  31. 14、models.NullBooleanField  允许为空的布尔类型

  32. 15、models.PositiveIntegerFiel  正Integer

  33. 16、models.PositiveSmallIntegerField  正smallInteger

  34. 17、models.SlugField  减号、下划线、字母、数字

  35. 18、models.SmallIntegerField  数字

  36.   数据库中的字段有:tinyint、smallint、int、bigint

  37. 19、models.TextField  字符串=longtext

  38. 20、models.TimeField  时间 HH:MM[:ss[.uuuuuu]]

  39. 21、models.URLField  字符串,地址正则表达式

  40. 22、models.BinaryField  二进制

  41. 23、models.ImageField 图片

  42. 24、models.FilePathField 文件

更多参数:

 
  1. 1、null=True

  2.   数据库中字段是否可以为空

  3. 2、blank=True

  4.   django的 Admin 中添加数据时是否可允许空值

  5. 3、primary_key = False

  6.   主键,对AutoField设置主键后,就会代替原来的自增 id 列

  7. 4、auto_now 和 auto_now_add

  8.   auto_now 自动创建---无论添加或修改,都是当前操作的时间

  9.   auto_now_add 自动创建---永远是创建时的时间

  10. 5、choices

  11. GENDER_CHOICE = (

  12. (u'M', u'Male'),

  13. (u'F', u'Female'),

  14. )

  15. gender = models.CharField(max_length=2,choices = GENDER_CHOICE)

  16. 6、max_length

  17. 7、default  默认值

  18. 8、verbose_name  Admin中字段的显示名称

  19. 9、name|db_column  数据库中的字段名称

  20. 10、unique=True  不允许重复

  21. 11、db_index = True  数据库索引

  22. 12、editable=True  在Admin里是否可编辑

  23. 13、error_messages=None  错误提示

  24. 14、auto_created=False  自动创建

  25. 15、help_text  在Admin中提示帮助信息

  26. 16、validators=[]

  27. 17、upload-to 上传到哪个位置,更多与image,filepath配合使用

连表结构

  1. 一对多:models.ForeignKey(其他表)
  2. 多对多:models.ManyToManyField(其他表)
  3. 一对一:models.ManyToManyField(其他表)

应用场景:

 
  1. 应用场景:

  2.  
  3. 一对多:当一张表中创建一行数据时,有一个单选的下拉框(可以被重复选择)

  4. 例如:创建用户信息时候,需要选择一个用户类型【普通用户】【金牌用户】【铂金用户】等。

  5. 多对多:在某表中创建一行数据是,有一个可以多选的下拉框

  6. 例如:创建用户信息,需要为用户指定多个爱好

  7. 一对一:在某表中创建一行数据时,有一个单选的下拉框(下拉框中的内容被用过一次就消失了

  8. 例如:原有含10列数据的一张表保存相关信息,经过一段时间之后,10列无法满足需求,需要为原来的表再添加5列数据

看个例子:

 
  1. from django.db import models

  2.  
  3. # Create your models here.

  4. from django.db import models

  5.  
  6. # 陈超,普通用户

  7. # 淮军,超级用户

  8. class Gender(models.Model):

  9. name = models.CharField(max_length=32)

  10.  
  11.  
  12. class userinfo(models.Model):

  13. nid = models.AutoField(primary_key=True)

  14. name = models.CharField(max_length=30, verbose_name='用户名',editable=False)

  15. email = models.EmailField(db_index=True)

  16. memo = models.TextField()

  17. img = models.ImageField(upload_to='upload')

  18. user_type = models.ForeignKey("UserType", null=True, blank=True)# unique

  19. # user_type = models.OneToOneField("UserType", null=True, blank=True)# unique

  20. # ctime = models.DateTimeField(auto_now_add=True)

  21. # uptime = models.DateTimeField(auto_now=True)

  22.  
  23. # gender = models.ForeignKey(Gender)

  24. gender_choices = (

  25. (0, "男"),

  26. (1, "女"),

  27. )

  28. gender = models.IntegerField(choices=gender_choices,default=1)

  29.  
  30. # 普通用户,超级用户

  31. class UserType(models.Model):

  32. name = models.CharField(max_length=32)

  33.  
  34. def __str__(self):

  35. return self.name

  36.  
  37. class B2G(models.Model):

  38. boy = models.ForeignKey('Boy')

  39. girl = models.ForeignKey('Girl')

  40.  
  41. class Boy(models.Model):

  42. name = models.CharField(max_length=32)

  43. # 吴文煜,王建,王志刚,杜宝强

  44.  
  45. class Girl(models.Model):

  46. name = models.CharField(max_length=32)

  47.  
  48. f = models.ManyToManyField(Boy)

  49. # 铁锤,钢弹,如花

TIPS:

  1. modles.py中class设置的数据,本身返回为一个类,如果想直接返回某一个字段的值,可以定义__str__,比如:

     
    1. class TypeUser(models.Model):

    2. name = models.CharFiled(max_length=32)

    3. def __str__(self):

    4. return self.name

  2. 在设置ForeignKey时,参数中的第一个参数为表名,**需要注意的是,加不加引号有区别:加引号后表的定义顺序可以随便,但不加引号必须按照顺序来:

     
    1. class userinfo(models.Model):

    2. nid = models.AutoField(primary_key=True)

    3. name = models.CharField(max_length=30, verbose_name='用户名',editable=False)

    4. email = models.EmailField(db_index=True)

    5. memo = models.TextField()

    6. img = models.ImageField(upload_to='upload')

    7. user_type = models.ForeignKey("UserType", null=True, blank=True)# unique

    8. # user_type = models.OneToOneField("UserType", null=True, blank=True)# unique

    9. # ctime = models.DateTimeField(auto_now_add=True)

    10. # uptime = models.DateTimeField(auto_now=True)

    11.  
    12. # gender = models.ForeignKey(Gender)

    13. gender_choices = (

    14. (0, "男"),

    15. (1, "女"),

    16. )

    17. gender = models.IntegerField(choices=gender_choices,default=1)

    18.  
    19. class UserType(models.Model):

    20. name = models.CharField(max_length=32)

    21. def __str__(self):

    22. return self.name

  3. 多对多,有两种创建方式

    1. 自建第三张表
    2. 自动创建,比如:

       
      1. #自建第三张表

      2. class B2G(models.Model):

      3. boy = models.ForeignKey('Boy')

      4. girl = models.ForeignKey('Girl')

      5.  
      6. class Boy(models.Model):

      7. name = models.CharField(max_length=32)

      8. # 吴文煜,王建,王志刚,杜宝强

      9.  
      10. class Girl(models.Model):

      11. name = models.CharField(max_length=32)

      12. #自动创建

      13. f = models.ManyToManyField(Boy)

    多对多详情参考:http://www.cnblogs.com/zknublx/p/5959295.html

  4. queryset

    从数据库中提取出来的数据为queryset类型,是Django中的一种特殊类型.

     
    1. w = models.Simp.objects.all()

    2. print(w, type(w))

    3. [<Simp: chenc>, <Simp: zan>, <Simp: zhangsan>]<class 'django.db.models.query.QuerySet'>

    可以看到,从数据库取出个数据看起来像包含对象的列表。而实际上整个数据为django中的特殊类型QuerySet。

    如果需要查看原来的SQL语句,可以使用queryset.query:

    print(w.query)
  5. values() 和 vlue_list() 与 all()区别

    .all()是取得所有列的数据,可以加.values()取出某一列,每一个元素为一个字典:

     
    1. obj = model.UserInfo.objects.filter(name='alex').values('id','email')

    2. # select id from userinfo where name = 'alex'

    3.  
    4. queryset -> python,Django的类

    5. [{'id':1},{'id': 2},]

    values_list(),获取到的元素为一个个元组,也可以加多个参数来获取多列:

     
    1. obj = model.UserInfo.objects.filter(name='alex').value_list('id','email')

    2. # select id from userinfo where name = 'alex'

    3.  
    4. queryset -> python,Django的类

    5. [(1,'[email protected]'),(2,'[email protected]'),]

表操作

基本操作

 
  1. # 增

  2. #

  3. # models.Tb1.objects.create(c1='xx', c2='oo') 增加一条数据,可以接受字典类型数据 **kwargs

  4.  
  5. # obj = models.Tb1(c1='xx', c2='oo')

  6. # obj.save()

  7.  
  8. # 查

  9. #

  10. # models.Tb1.objects.get(id=123) # 获取单条数据,不存在则报错(不建议)

  11. # models.Tb1.objects.all() # 获取全部

  12. # models.Tb1.objects.filter(name='seven') # 获取指定条件的数据

  13.  
  14. # 删

  15. #

  16. # models.Tb1.objects.filter(name='seven').delete() # 删除指定条件的数据

  17.  
  18. # 改

  19. # models.Tb1.objects.filter(name='seven').update(gender='0') # 将指定条件的数据更新,均支持 **kwargs

  20. # obj = models.Tb1.objects.get(id=1)

  21. # obj.c1 = '111'

  22. # obj.save() # 修改单条数据

  23.  

进阶操作(了不起的双下划线)

利用双下划线将字段和对应的操作连接起来

 
  1. # 获取个数

  2. #

  3. # models.Tb1.objects.filter(name='seven').count()

  4.  
  5. # 大于,小于

  6. #

  7. # models.Tb1.objects.filter(id__gt=1) # 获取id大于1的值

  8. # models.Tb1.objects.filter(id__lt=10) # 获取id小于10的值

  9. # models.Tb1.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值

  10.  
  11. # in

  12. #

  13. # models.Tb1.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据

  14. # models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in

  15.  
  16. # contains

  17. #

  18. # models.Tb1.objects.filter(name__contains="ven")

  19. # models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感

  20. # models.Tb1.objects.exclude(name__icontains="ven")

  21.  
  22. # range

  23. #

  24. # models.Tb1.objects.filter(id__range=[1, 2]) # 范围bettwen and

  25.  
  26. # 其他类似

  27. #

  28. # startswith,istartswith, endswith, iendswith,

  29.  
  30. # order by

  31. #

  32. # models.Tb1.objects.filter(name='seven').order_by('id') # asc

  33. # models.Tb1.objects.filter(name='seven').order_by('-id') # desc

  34.  
  35. # limit 、offset

  36. #

  37. # models.Tb1.objects.all()[10:20]

  38.  
  39. # group by

  40. from django.db.models import Count, Min, Max, Sum

  41. # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))

  42. # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"

  43.  

连表操作(了不起的双下划线)

利用双下划线和 _set 将表之间的操作连接起来

数据库表结构:

 
  1. class UserProfile(models.Model):

  2. user_info = models.OneToOneField('UserInfo')

  3. username = models.CharField(max_length=64)

  4. password = models.CharField(max_length=64)

  5.  
  6. def __unicode__(self):

  7. return self.username

  8.  
  9.  
  10. class UserInfo(models.Model):

  11. user_type_choice = (

  12. (0, u'普通用户'),

  13. (1, u'高级用户'),

  14. )

  15. user_type = models.IntegerField(choices=user_type_choice)

  16. name = models.CharField(max_length=32)

  17. email = models.CharField(max_length=32)

  18. address = models.CharField(max_length=128)

  19.  
  20. def __unicode__(self):

  21. return self.name

  22.  
  23.  
  24. class UserGroup(models.Model):

  25.  
  26. caption = models.CharField(max_length=64)

  27.  
  28. user_info = models.ManyToManyField('UserInfo')

  29.  
  30. def __unicode__(self):

  31. return self.caption

  32.  
  33.  
  34. class Host(models.Model):

  35. hostname = models.CharField(max_length=64)

  36. ip = models.GenericIPAddressField()

  37. user_group = models.ForeignKey('UserGroup')

  38.  
  39. def __unicode__(self):

  40. return self.hostname

  41.  

一对一操作:

 
  1. user_info_obj = models.UserInfo.objects.filter(id=1).first()

  2. print user_info_obj.user_type

  3. print user_info_obj.get_user_type_display()

  4. print user_info_obj.userprofile.password

  5.  
  6. user_info_obj = models.UserInfo.objects.filter(id=1).values('email', 'userprofile__username').first()

  7. print user_info_obj.keys()

  8. print user_info_obj.values()

一对多操作,类似于一对一:

 
  1. 1、搜索条件使用 __ 连接

  2. 2、获取值时使用 . 连接

多对多操作:

 
  1. user_info_obj = models.UserInfo.objects.get(name=u'武沛齐')

  2. user_info_objs = models.UserInfo.objects.all()

  3.  
  4. group_obj = models.UserGroup.objects.get(caption='CEO')

  5. group_objs = models.UserGroup.objects.all()

  6.  
  7. # 添加数据

  8. #group_obj.user_info.add(user_info_obj)

  9. #group_obj.user_info.add(*user_info_objs)

  10.  
  11. # 删除数据

  12. #group_obj.user_info.remove(user_info_obj)

  13. #group_obj.user_info.remove(*user_info_objs)

  14.  
  15. # 添加数据

  16. #user_info_obj.usergroup_set.add(group_obj)

  17. #user_info_obj.usergroup_set.add(*group_objs)

  18.  
  19. # 删除数据

  20. #user_info_obj.usergroup_set.remove(group_obj)

  21. #user_info_obj.usergroup_set.remove(*group_objs)

  22.  
  23. # 获取数据

  24. #print group_obj.user_info.all()

  25. #print group_obj.user_info.all().filter(id=1)

  26.  
  27. # 获取数据

  28. #print user_info_obj.usergroup_set.all()

  29. #print user_info_obj.usergroup_set.all().filter(caption='CEO')

  30. #print user_info_obj.usergroup_set.all().filter(caption='DBA')

其他操作:

 
  1. # F 使用查询条件的值

  2. #

  3. # from django.db.models import F

  4. # models.Tb1.objects.update(num=F('num')+1)

  5.  
  6. # Q 构建搜索条件

  7. from django.db.models import Q

  8. # con = Q()

  9. #

  10. # q1 = Q()

  11. # q1.connector = 'OR'

  12. # q1.children.append(('id', 1))

  13. # q1.children.append(('id', 10))

  14. # q1.children.append(('id', 9))

  15. #

  16. # q2 = Q()

  17. # q2.connector = 'OR'

  18. # q2.children.append(('c1', 1))

  19. # q2.children.append(('c1', 10))

  20. # q2.children.append(('c1', 9))

  21. #

  22. # con.add(q1, 'AND')

  23. # con.add(q2, 'AND')

  24. #

  25. # models.Tb1.objects.filter(con)

  26.  
  27. #

  28. # from django.db import connection

  29. # cursor = connection.cursor()

  30. # cursor.execute("""SELECT * from tb where name = %s""", ['Lennon'])

  31. # row = cursor.fetchone()

  32.  

xx_set中的_set是多对多的固定搭配

扩展

自定义上传

 
  1. def upload_file(request):

  2. if request.method == "POST":

  3. obj = request.FILES.get('fafafa')

  4. f = open(obj.name, 'wb')

  5. for chunk in obj.chunks():

  6. f.write(chunk)

  7. f.close()

  8. return render(request, 'file.html')

form上传文件实例

 
  1. class FileForm(forms.Form):

  2. ExcelFile = forms.FileField()

models.py:

 
  1. from django.db import models

  2.  
  3. class UploadFile(models.Model):

  4. userid = models.CharField(max_length = 30)

  5. file = models.FileField(upload_to = './upload/')

  6. date = models.DateTimeField(auto_now_add=True)

view.py:

 
  1. def UploadFile(request):

  2. uf = AssetForm.FileForm(request.POST,request.FILES)

  3. if uf.is_valid():

  4. upload = models.UploadFile()

  5. upload.userid = 1

  6. upload.file = uf.cleaned_data['ExcelFile']

  7. upload.save()

  8.  
  9. print upload.file

猜你喜欢

转载自blog.csdn.net/qq_42332688/article/details/85262761