Django admin, custom error message?(Django 管理员,自定义错误消息?)
问题描述
我想知道如何在 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 管理员,自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django 管理员,自定义错误消息?
基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
