2

我有一个模型

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 模板吗?

  • 当我将它扔到模型上的 Group.save() 上时,它会破坏页面,而不是不保存并告诉用户修复错误。
  • 起初我没有使用 AdminForm,但使用它意味着验证已运行,并且它请求更改(请更正下面的错误。),但它不显示 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 %}

4

1 回答 1

3

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

表格.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
于 2018-04-09T13:21:42.070 回答