Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

validation - 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.detail', args=(project.id,)))
    else:
        formset = MilestoneFormSet2(queryset=qs, prefix='new')
    return render_to_response('project/manageMilestones.html', {
        'formset': formset,
    }, context_instance=RequestContext(request))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...