* 本文代码同步更新至 https://github.com/yinzhuoqun/django2 *
django admin 后台里有些输入框长度、宽度、提示语等,可能不满足我们的需求,这个时候,我们就需要对 admin 的样式进行更改。
还是先从 django 官网 找文档,发现 widget 是可以再 admin.py 里面重写的,只需要用到 django.contrib.admin.ModelAdmin.formfield_overrides(这个属性通过一种临时的方案来覆盖现有的模型中 Field (字段)类型在admin site中的显示类型。formfield_overrides 在类初始化的时候通过一个字典类型的变量来对应模型字段类型与实际重载类型的关系。)
方法一: 只改 admin.py ,缺点是 只能针对某种字段类型,不能指定字段。
# admin.py
代码语言:javascript复制from django.contrib import admin
from django.forms import widgets
from apps.blog.models import *
class ArticleAdmin(admin.ModelAdmin):
list_display = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'show_status', 'slug', 'user']
list_display_links = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'user']
search_fields = ['title_short', 'user', 'content']
list_editable = ["show_status", ]
# style_fields = {"content": "ueditor"}
readonly_fields = ('slug',)
show_detail_fields = ['show_status', ]
# 重写 字段类型 的 widget, attrs 属性可以设置前端样式
formfield_overrides = {
models.IntegerField: {'widget': widgets.NumberInput(attrs={"style": "width:50em;", })},
models.CharField: {'widget': widgets.TextInput(attrs={"style": "width:50%;", "placeholder": "请输入内容"})},
}
admin.site.register(Article, ArticleAdmin)
方法二:此方法可以指定字段,而不是字段类型。
来源:https://timonweb.com/posts/override-field-widget-in-django-admin-form/
1. 首先 在 forms.py 新建一个 表单 ArticleAdminFrom
# forms.py
代码语言:javascript复制#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: yinzhuoqun
@site: http://zhuoqun.info/
@email: yin@zhuoqun.info
@time: 2019/9/5 15:26
"""
from django import forms
from django.forms.widgets import TextInput
from apps.blog.models import Article
class ArticleAdminForm(forms.ModelForm):
class Meta:
model = Article
fields = '__all__'
widgets = {
"title": TextInput(attrs={"style": "width:50%;", "placeholder": "请输入标题"}),
}
2. 然后在 admin.py 里面启用自定义的 ArticleAdminForm
# admin.py
代码语言:javascript复制from django.contrib import admin
from django.forms import widgets
from apps.blog.models import *
from apps.blog.forms import ArticleAdminForm
class ArticleAdmin(admin.ModelAdmin):
form = ArticleAdminForm # 指定了表单,就不要再用 formfield_overrides 了
list_display = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'show_status', 'slug', 'user']
list_display_links = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'user']
search_fields = ['title_short', 'user', 'content']
list_editable = ["show_status", ]
# style_fields = {"content": "ueditor"}
readonly_fields = ('slug',)
show_detail_fields = ['show_status', ]
# 重写 字段类型 的 widget, attrs 属性可以设置前端样式
# formfield_overrides = {
# models.IntegerField: {'widget': widgets.NumberInput(attrs={"style": "width:50em;", })},
# models.CharField: {'widget': widgets.TextInput(attrs={"style": "width:50%;", "placeholder": "请输入内容"})},
# }
admin.site.register(Article, ArticleAdmin)
# 本文使用的 Article Model
https://github.com/yinzhuoqun/django2/blob/master/apps/blog/models.py
# 效果