我想知道如何在 Django admin 中显示错误消息.
I would like to know how to show an error message in the Django admin.
我的网站上有一个私人用户部分,用户可以在其中使用点"创建请求.一个请求从用户的帐户中获得 1 或 2 分(取决于两种类型的请求),所以如果帐户有 0 分,则用户不能提出任何请求......在私人用户部分,这一切都很好,但是用户也可以致电公司并通过电话提出请求,在这种情况下,我需要管理员在用户积分为 0 的情况下显示自定义错误消息.
I have a private user section on my site where the user can create requests using "points". A request takes 1 or 2 points from the user's account (depending on the two type of request), so if the account has 0 points the user cant make any requests... in the private user section all this is fine, but the user can also call the company and make a request by phone, and in this case I need the admin to show a custom error message in the case of the user points being 0.
任何帮助都会很好:)
谢谢大家
一种方法是覆盖管理页面的 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)
希望有帮助!
这篇关于Django 管理员,自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!