Django管理员,自定义错误消息? [英] Django admin, custom error message?

查看:324
本文介绍了Django管理员,自定义错误消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在Django管理员中显示错误消息。



我的网站上有一个私人用户部分,用户可以使用该部分创建请求点。一个请求需要用户帐户的1或2分(取决于两种类型的请求),所以如果该帐户有0分,则用户无法在私人用户部分中发出任何请求,所有这一切都是正常的,但用户也可以打电话给公司并通过电话提出请求,在这种情况下,我需要管理员在用户分数为0的情况下显示自定义错误消息。



任何帮助都会很好:)



谢谢你们

解决方案

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

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

class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def clean_points(self):
points = self .cleaned_data ['points']
如果points.isdigit()和点< 1:
raise forms.ValidationError(你没有点!)
返回点

class MyModelAdmin(admin.ModelAdmin):
form = MyForm

admin.site.register(MyModel,MyModelAdmin)

希望有帮助! / p>

I would like to know how to show an error message in the Django admin.

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.

Any help will be nice :)

Thanks guys

解决方案

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)

Hope that helps!

这篇关于Django管理员,自定义错误消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆