且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django 管理员,自定义错误消息?

更新时间:2023-01-29 22:49:51

一种方法是覆盖管理页面的 ModelForm.这允许您编写自定义验证方法并非常干净地返回您选择的错误.像这样在 admin.py 中:

One way to do that is by overriding the ModelForm for the admin page. That allows you to write custom validation methods and return errors of your choosing very cleanly. Like this in admin.py:

from django.contrib import admin
from models import *
from django import forms

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
    def clean_points(self):
        points = self.cleaned_data['points']
        if points.isdigit() and points < 1:
            raise forms.ValidationError("You have no points!")
        return points

class MyModelAdmin(admin.ModelAdmin):
    form = MyForm

admin.site.register(MyModel, MyModelAdmin)

希望有帮助!