Django的ModelForm unique_together验证 [英] Django's ModelForm unique_together validation
问题描述
我有一个看起来像这样的Django模型。
class Solution(models.Model):
pre>
' ''
代表具体问题的解决方案。
'''
name = models.CharField(max_length = 50)
problem = models.ForeignKey(问题)
description = models.TextField(blank = True)
date = models.DateTimeField(auto_now_add = True)
class Meta:
unique_together =(name,problem)
我使用一个表单来添加如下所示的模型:
class SolutionForm(forms.ModelForm):
class Meta:
model = Solution
exclude = ['problem']
我的问题是,
SolutionForm
不验证解决方案
的unique_together
约束,因此,它将返回一个IntegrityError
试图保存的形式时。我知道我可以使用validate_unique
来手动检查这一点,但是我想知道是否有任何方法可以在验证形式中捕获这一点,并自动返回一个表单错误。 >
谢谢。
解决方案我设法解决这个问题,而不修改视图一个干净的方法我的形式:
class SolutionForm(forms.ModelForm):
class Meta:
模型=解决方案
排除= [ '问题']
高清干净(个体经营):
cleaned_data = self.cleaned_data
尝试:
Solution.objects.get(name = clean_data ['name'],problem = self.problem)
除了Solution.DoesNotExist:
pass
else:
raise ValidationError('这个名称已经存在这个问题)
#解决方案总是返回cleaned_data
返回cleaned_data
在视图中我唯一需要做的是在执行
is_valid
之前在表单中添加一个问题属性。I have a Django model that looks like this.
class Solution(models.Model): ''' Represents a solution to a specific problem. ''' name = models.CharField(max_length=50) problem = models.ForeignKey(Problem) description = models.TextField(blank=True) date = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ("name", "problem")
I use a form for adding models that looks like this:
class SolutionForm(forms.ModelForm): class Meta: model = Solution exclude = ['problem']
My problem is that the
SolutionForm
does not validateSolution
'sunique_together
constraint and thus, it returns anIntegrityError
when trying to save the form. I know that I could usevalidate_unique
to manually check for this but I was wondering if there's any way to catch this in the form validation and return a form error automatically.Thanks.
解决方案I managed to fix this without modifying the view by adding a clean method to my form:
class SolutionForm(forms.ModelForm): class Meta: model = Solution exclude = ['problem'] def clean(self): cleaned_data = self.cleaned_data try: Solution.objects.get(name=cleaned_data['name'], problem=self.problem) except Solution.DoesNotExist: pass else: raise ValidationError('Solution with this Name already exists for this problem') # Always return cleaned_data return cleaned_data
The only thing I need to do now in the view is to add a problem property to the form before executing
is_valid
.这篇关于Django的ModelForm unique_together验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!