如何为DjangoAdmin抛出ValidationError,当它是一个ModelAdmin w / change_view

时间:2018-03-26 17:00:05

标签: django django-forms django-admin django-admin-tools

我有一个模特

class Group(models.Model):
    active = models.BooleanField(null=False, blank=False, default=True)

及其管理页面

class GroupAdmin(admin.ModelAdmin):
    change_form_template = "admin/group/group.html"
    form = GroupAdminForm

    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['group_data'] = self.get_info(object_id)
        return super(GroupAdmin, self).change_view(
            request, object_id, form_url, extra_context=extra_context,
        )

class GroupAdminForm(ModelForm):
    class Meta:
        model = Group
        fields = '__all__'

    def clean_active(self):
        active = self.cleaned_data['active']

        if 'active' in self.changed_data and not active and OtherCondition:
            raise ValidationError('Group must stay active because of OtherCondition')
        return active

需要change_view模板。

由于change_view模板,验证错误未显示。

如何抛出验证错误并将其显示在Django管理员身上?有没有办法使用ValidationError执行此操作?是通过更改change_view模板吗?

  • 当我在Model上的Group.save()上抛出它时,它会破坏页面,而不是不保存并告诉用户修复错误。
  • 起初我没有使用AdminForm,但是使用它意味着运行验证,它会请求更改(请更正以下错误。),但它没有&#39 ; t显示ValidationError消息。

此问题类似,但建议使用消息,但我想知道是否有另一种方式:Raise django admin validation error from a custom view

我不认为我特别包含了字段错误,但我认为它应该通过django提供的html包含它们:

admin/change_form

{% block field_sets %}
{% for fieldset in adminform %}
  {% include "admin/includes/fieldset.html" %}
{% endfor %}
{% endblock %}

admin/includes/fieldset.html{{ line.errors }}。也许是将错误传递给change_view?

group.html按要求提供。

{% extends "admin/change_form.html" %}
{%  block field_sets %}
    {# stuff #}
    {{ block.super }}
{%  endblock %}

{% block inline_field_sets %}
{% for inline_admin_formset in inline_admin_formsets %}
    {# stuff #}
{% endfor %}
{% endblock %}

{# M2M Preview #}
{% block after_related_objects %}
    {# stuff #}
{%  endblock %}

1 个答案:

答案 0 :(得分:2)

我认为在这种情况下,表单验证是一个好主意。

<强> forms.py

class YourForm(forms.ModelForm):

    def clean(self):
        super(YourForm, self).clean()
        data1 = self.cleaned_data.get('data1')
        data2 = self.cleaned_data.get('data2')

        # Add validation condition here
        # if validation error happened you can raise the error 
        # and attach the error message with the field you want.

        self.add_error('field_name', 'error message')

admin.py

 class YourAdminClass(admin.ModelAdmin):
     form = YourForm