我正在尝试创建一个验证规则,如果(里程碑)对象target_date大于项目target_date,则传递错误。问题是没有出现任何错误。
为了简单起见,
models.py
class Project(models.Model):
target_date = models.DateField()
class Milestone(models.Model):
project = models.ForeignKey(Project)
target_date = models.DateField()
Forms.py
class MilestoneAddForm(forms.ModelForm):
class Meta:
model = Milestone
def clean_target_date(self):
tdate = self.cleaned_data['target_date']
if tdate > self.instance.project.target_date
raise forms.ValidationError("Target Date is outside or project target date.")
return tdate
views.py(删除不相关的代码)
def MilestoneManage(request, project_id):
qs = Project.objects.none()
if request.method == 'POST':
formset = MilestoneFormSet(request.POST, prefix='new')
if formset.is_valid():
newMiles = formset.save(commit=False)
for new in newMiles:
new.project_id = project.id
new.save()
return HttpResponseRedirect(reverse('project.views.detail', args=(project.id,)))
else:
formset = MilestoneFormSet2(queryset=qs, prefix='new')
return render_to_response('project/manageMilestones.html', {
'formset': formset,
}, context_instance=RequestContext(request))
答案 0 :(得分:1)
这应该有效。有关更改内容的详细信息,请参阅内联注释。
def clean_target_date(self):
# V-- typo (cleand_data => cleaned_data)
tdate = self.cleaned_data['target_date']
project = self.instance.project
# project allows for nulls, so check that first.
if project is None:
raise forms.ValidationError("There's no project associated with this milestone.")
# V-- Do an attribute lookup, don't use the query lookup syntax
if tdate > project.target_date:
raise forms.ValidationError("Target Date is outside or project target date.")
return tdate