来源:http://xieboke.net/article/100/
django admin 后台里有些输入框长度、宽度、提示语等,可能不满足我们的需求,这个时候,我们就需要对 admin 的样式进行更改。 还是先从 django 官网 找文档,发现 widget 是可以再 admin.py 里面重写的,只需要用到 django.contrib.admin.ModelAdmin.formfield_overrides(这个属性通过一种临时的方案来覆盖现有的模型中 Field (字段)类型在admin site中的显示类型。formfield_overrides 在类初始化的时候通过一个字典类型的变量来对应模型字段类型与实际重载类型的关系。)
方法一: 只改 admin.py ,缺点是 只能针对某种字段类型,不能指定字段。
# admin.py
1 from django.contrib import admin 2 from django.forms import widgets 3 from apps.blog.models import * 4 5 6 class ArticleAdmin(admin.ModelAdmin): 7 list_display = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'show_status', 'slug', 'user'] 8 list_display_links = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'user'] 9 search_fields = ['title_short', 'user', 'content'] 10 list_editable = ["show_status", ] 11 # style_fields = {"content": "ueditor"} 12 readonly_fields = ('slug',) 13 show_detail_fields = ['show_status', ] 14 15 # 重写 字段类型 的 widget, attrs 属性可以设置前端样式 16 formfield_overrides = { 17 models.IntegerField: {'widget': widgets.NumberInput(attrs={"style": "width:50em;", })}, 18 models.CharField: {'widget': widgets.TextInput(attrs={"style": "width:50%;", "placeholder": "请输入内容"})}, 19 } 20 21 22 admin.site.register(Article, ArticleAdmin)
方法二:此方法可以指定字段,而不是字段类型。 来源:https://timonweb.com/posts/override-field-widget-in-django-admin-form/
1. 首先 在 forms.py 新建一个 表单 ArticleAdminFrom # forms.py
1 from django import forms 2 from django.forms.widgets import TextInput 3 from apps.blog.models import Article 4 5 6 class ArticleAdminForm(forms.ModelForm): 7 class Meta: 8 model = Article 9 fields = '__all__' 10 widgets = { 11 "title": TextInput(attrs={"style": "width:50%;", "placeholder": "请输入标题"}), 12 }
2. 然后在 admin.py 里面启用自定义的 ArticleAdminForm # admin.py
1 from django.contrib import admin 2 from django.forms import widgets 3 from apps.blog.models import * 4 from apps.blog.forms import ArticleAdminForm 5 6 7 class ArticleAdmin(admin.ModelAdmin): 8 form = ArticleAdminForm # 指定了表单,就不要再用 formfield_overrides 了 9 10 list_display = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'show_status', 'slug', 'user'] 11 list_display_links = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'user'] 12 search_fields = ['title_short', 'user', 'content'] 13 list_editable = ["show_status", ] 14 # style_fields = {"content": "ueditor"} 15 readonly_fields = ('slug',) 16 show_detail_fields = ['show_status', ] 17 18 # 重写 字段类型 的 widget, attrs 属性可以设置前端样式 19 # formfield_overrides = { 20 # models.IntegerField: {'widget': widgets.NumberInput(attrs={"style": "width:50em;", })}, 21 # models.CharField: {'widget': widgets.TextInput(attrs={"style": "width:50%;", "placeholder": "请输入内容"})}, 22 # } 23 24 25 admin.site.register(Article, ArticleAdmin)
标签:widget,show,admin,fields,django,设置,import From: https://www.cnblogs.com/ldx-wsj/p/17125306.html