django - 创建完美 django 自定义验证的问题
问题描述
我的会计应用程序有这个模型:
class Simpleunits(models.Model):
User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
symbol = models.CharField(max_length=32)
formal = models.CharField(max_length=32)
class Compoundunits(models.Model):
User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
firstunit = models.ForeignKey(Simpleunits,on_delete=models.CASCADE)
conversion = models.DecimalField(max_digits=19,decimal_places=2)
secondunit = models.ForeignKey(Simpleunits,on_delete=models.CASCADE)
class Stockdata(models.Model):
User = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True)
stock_name = models.CharField(max_length=32)
unitsimple = models.ForeignKey(Simpleunits,on_delete=models.CASCADE,null=True,blank=True)
unitcomplex = models.ForeignKey(Compoundunits,on_delete=models.CASCADE,null=True,blank=True)
我想在模型类 Stockdata 下创建一个自定义验证方法,如果用户同时提到 unitsimple 和 unitcomplex,那么他们将收到“只应给出一个单位”的验证错误,反之亦然......
我的意思是说,如果用户同时提及两个单元,则只能提及一个单元,无论是 unitsimple 还是 unitcomplex,那么他们将收到验证错误...
有谁知道我应该在 def clean(self) 函数下做什么来完成这个..???
先感谢您...
解决方案
为 Stockdata 的创建视图创建一个模型表单,如您所说,添加一个自定义 clean() 方法,如下所示。
class CreateStockData(forms.ModelForm):
class Meta:
model = Stockdata
fields= [....]
....
def clean(self):
cleaned_data = super(CreateStockData, self).clean()
unitsimple = cleaned_data.get('unitsimple')
unitcomplex = cleaned_data.get('unitcomplex')
if unitsimple != None and unitcomplex != None:
raise forms.ValidationError({'unitcomplex':["You are not supposed to select both values!"]})
编辑
鉴于您的评论,让我以另一种方式发布。
class Stockdata(models.Model):
....
def clean(self):
if self.unitsimple is not None and if self.unitcomplex is not None:
raise ValidationError(
{'unitcomplex':["You are not supposed to select both values!"]})
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)
请参阅验证对象
推荐阅读
- excel - Selection.AutoFill Destination 无法按预期工作
- archunit - 使用 ArchUnit 测试模块中的包依赖关系
- php - 对 PHP API 客户端进行单元测试
- python - Spacy 的问题 - ModuleNotFoundError:没有名为“sudachidict”的模块
- javascript - 切换选项卡时传单离开 OSM 地图路线
- java - 如何通过单个 rest api 调用从 box.com 批量下载具有协作和文件信息的文件?
- java - 使用java,如何在elasticsearch中将匹配查询的默认运算符更改为AND?
- html - 向带有选择和标签的 div 添加箭头
- oauth-2.0 - WSO2:端点是一个休息服务,它有自己的 oauth2 服务。是否有可能在 WSO2 中为一个 API 禁用身份验证?
- python - 使用 tokenizer.encode_plus 的麻烦