我有一个模特
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模板吗?
此问题类似,但建议使用消息,但我想知道是否有另一种方式:Raise django admin validation error from a custom view
我不认为我特别包含了字段错误,但我认为它应该通过django提供的html包含它们:
{% 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 %}
答案 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