views:

30

answers:

1

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))
+1  A: 

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
sdolan
Nice, it runs now but not throwing an error.
Dronestudios
@Dronestudios: Are you sure target_date is greater than the projects' target_date? What happens if you debug into it?
sdolan
Still a relatively new at django and my debugging foo is weak at the moment. It will most likely take me a little bit to figure out what's going on. It seems as if none of this code is getting called.
Dronestudios
It may be, try throwing in a `raise` at the beginning of `cleaned_target_date`. If you don't see an exception then it's not being called. If this happens, update your question with your `Milestone` model definition.
sdolan
Yeah it looks like even doing that isn't happening. Could this be due to using formsets? Added views.py
Dronestudios
Yeah, it works on my normal forms. There must be something different about formsets.
Dronestudios