管理中的 django ValidationError save_model
django ValidationError in admin save_model
Models.py
class user(AbstractUser):
salary_number = models.IntegerField(unique=True, null=True, blank=True)
Admin.py
def save_model(self, request, obj, form, change):
if obj.salary_number == None:
raise ValidationError("ERROR salary number!")
....
obj.save()
如果用户忘记填写工资号码,我试图向他们显示错误,但我在 /admin/information/user/add/ 处收到错误 ValidationError。我该如何解决?
我有理由不设置 salary_number null & blank = False。
最简单的方法大概就是做一个小的ModelForm
:
from django import forms
from django.core.exceptions import ValidationError
class UserModelForm(forms.ModelForm):
def <strong>clean_salary_number</strong>(self):
data = self.cleaned_data['salary_number']
if data is None:
raise ValidationError('ERROR salary number!')
return data
然后将其插入 ModelAdmin
:
from django.contrib import admin
class MyModelAdmin(admin.ModelAdmin):
# …
<strong>form = UserModelForm</strong>
Models.py
class user(AbstractUser):
salary_number = models.IntegerField(unique=True, null=True, blank=True)
Admin.py
def save_model(self, request, obj, form, change):
if obj.salary_number == None:
raise ValidationError("ERROR salary number!")
....
obj.save()
如果用户忘记填写工资号码,我试图向他们显示错误,但我在 /admin/information/user/add/ 处收到错误 ValidationError。我该如何解决?
我有理由不设置 salary_number null & blank = False。
最简单的方法大概就是做一个小的ModelForm
:
from django import forms
from django.core.exceptions import ValidationError
class UserModelForm(forms.ModelForm):
def <strong>clean_salary_number</strong>(self):
data = self.cleaned_data['salary_number']
if data is None:
raise ValidationError('ERROR salary number!')
return data
然后将其插入 ModelAdmin
:
from django.contrib import admin
class MyModelAdmin(admin.ModelAdmin):
# …
<strong>form = UserModelForm</strong>