How to validate a Django Form field against a FK field
I am attempting to create a validation rule that passes an error if the (milestone)objects target_date is greater then the projects target_date. The issue is that none of the errors are being raised.
For simplicities sake,
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(dropped unrelated code)
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.de开发者_C百科tail', args=(project.id,)))
else:
formset = MilestoneFormSet2(queryset=qs, prefix='new')
return render_to_response('project/manageMilestones.html', {
'formset': formset,
}, context_instance=RequestContext(request))
This should work. See inline comments for more info on what was changed.
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
精彩评论