且构网

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

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

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

一种方法是覆盖管理页面的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!