Django管理表单字段属性覆盖

时间:2016-12-20 11:47:27

标签: django django-forms django-admin

Django 1.8。我有模特:

class Location(models.Model):
    address = models.CharField(max_length=65)
    annotation = models.CharField(
        max_length=80, verbose_name='Additional info', blank=True, null=True,
        help_text='e.g. officce 412, 4 floor')

我的任务是在Location中为admin.py扩展表单输入字段。我是这样做的:

class LocationAdminForm(forms.ModelForm):
    annotation = forms.CharField(
        widget=forms.widgets.TextInput(attrs={'size': 70}))

此处我在管理员表单中丢失了verboose_nameblank=Truehelp_text。我可以通过以下方式解决这个问题:

class LocationAdminForm(forms.ModelForm):
    annotation = forms.CharField(
        required=not Location._meta.get_field('annotation').blank,
        label=Location._meta.get_field('annotation').verbose_name,
        help_text=Location._meta.get_field('annotation').help_text,
        widget=forms.widgets.TextInput(attrs={'size': 70}))

但是这个变种看起来很难看......这里还有其他选择吗?

1 个答案:

答案 0 :(得分:1)

我强烈建议您修改此管理模型的css,而不是更改表单/字段,请参阅ModelAdmin asset definitions

class LocationAdmin(admin.ModelAdmin):
    class Media:
        css = {
            "all": ("location_admin.css",)
        }

myapp/static/location_admin.css

#id_annotation { width: 423px }