天天看点

【Django】model and admin

model
  • django 中的一个model 对应数据库中的一张表 以类的形式表现

例子:

from django.db import models

# Create your models here.

class Article(models.Model)
	title=models.CharField(max_length=30,default='title')
	content=models.CharField(null=True)
           

要在数据库中创建这个表

要使用manage.py 

python manage.py makemigrations
python manage.py migrate
           
admin
  • 创建管理员

可以在控制台输入 然后输入账号密码

python manage.py createsuperuser
           

也可以在后台admin页面中创建

  • 修改后台admin页面展示

例子:

list_display 表示展示列名  不单单只能用表中的属性,也可以自己定义 方式见下

list_per_page 表示每页数据

search_fields 表示可以用来搜索的列

@admin.register(models.UserInfo)
class UserAdmin(admin.ModelAdmin):

    list_display = ['id', 'user_name', 'email', 'user_img_show']
    list_per_page = 10
    search_fields = ['user_name', ]

@admin.register(models.Matchup)
class MatchAdmin(admin.ModelAdmin):
    list_display = ('id','matchup_u', 'matchup_p', 'matchup_t')

    def matchup_u(self, obj):
        return '%s' % obj.matchup_user.user_name
    matchup_u.short_description = '用户'

    def matchup_p(self, obj):
        return format_html(
                '<img src="{}" width="50px"/>',
                obj.matchup_picture.img_address.url,
            )
    matchup_p.short_description = '照片'

    def matchup_t(self, obj):
        return '%s' % obj.matchup_tag.tag_description
    matchup_t.short_description = '标签'