验证管理员内联表单

时间:2017-01-12 09:43:47

标签: python django django-admin

我是Admin界面,我需要验证内联中的字段。 网站名称必须以小写形式存储。

如何访问内联中的名称字段以执行该验证?

我也可以在模型中覆盖其保存方法,但我想知道如何在管理中执行此操作。

class SiteInline(admin.TabularInline):
    model = Site
    classes = ('grp-collapse grp-open',)
    inline_classes = ('grp-collapse grp-open',)


class CompanyAdmin(admin.ModelAdmin):
    ordering = ['name']
    inlines = (SiteInline, )

1 个答案:

答案 0 :(得分:1)

您可以使用Regex验证该字段。

<强> admin.py

from django import forms
from django.contrib import admin
from django.core import validators
from django.utils.translation import ugettext_lazy as _

from .models import Company, Site


class SiteInlineAdminForm(forms.ModelForm):
    name = forms.CharField(max_length=16,
        help_text=_('Required. lower case character For Example: test'),
        validators=[
            validators.RegexValidator(r'^[a-z]*$',
                message=_('Enter a valid name. This value may contain only lower case character.')),
        ])

    class Meta:
        model = Site
        exclude = ()


class SiteInline(admin.TabularInline):
    model = Site
    form = SiteInlineAdminForm
    classes = ('grp-collapse grp-open',)
    inline_classes = ('grp-collapse grp-open',)


class CompanyAdmin(admin.ModelAdmin):
    ordering = ['name']
    inlines = (SiteInline, )


admin.site.register(Company, CompanyAdmin)