views:

63

answers:

2

Hi all,

It's simple - All I want to do is set who answered the question if the question is answered. Can someone please enlighten me on how to set a form value if the question was answered. I know that I could also set this as an initial value but then I have to selectively determine which records were answered. This seemed simpler but I'm pulling my hair out tryig to figure this out. Can someone help me out.

The model is simple enough

class ProjectQuestion(models.Model):
    question = models.CharField(max_length=255, editable=True)
    answer_type = models.CharField(max_length=50, choices=VALUE_TYPE_CHOICES, editable=True)
    answer = models.CharField(max_length=255, null=True, blank=True)
    answer_comment = models.TextField(blank = True, null = True)
    answered_by = models.ForeignKey(Employee, related_name="answered_by_test", null=True, blank=True)
    answer_date = models.DateTimeField(auto_now = True, null=True)
    objects = models.Manager()


    def __unicode__(self):
        return u'%s' % (self.question)

And the representing view is also simple.

# views.py
if request.method == "POST":
    print request.POST
    print request.user
    formset = QuestionFormSet(data=request.POST, files=request.FILES,
                              queryset=ProjectQuestion.objects.filter(id__lt=shortname))
    print formset.forms
    if formset.is_valid():
        person =  Employee.objects.get(name__iexact = request.user.get_full_name())
        for i in range(0, formset.total_form_count()):
            form = formset.forms[i]
            if form.cleaned_data['answer']:
                # THIS DOESN'T WORK...  PLEASE FIX..
                form.save(commit=False)
                form.answered_by = person
                form.save()
else:
    active_section = ProjectQuestion.objects.filter(id__lt=shortname)
+2  A: 

isn't it supposed to be

if form.cleaned_data['answer']:
    # THIS DOESN'T WORK...  PLEASE FIX..
    question = form.save(commit=False)
    question.answered_by = person
    question.save()
Ashok
A: 

Ashok has the right answer - form.save returns the instance object, saved or not depending on the value of commit.

As a side issue, note that this:

    for i in range(0, formset.total_form_count()):
        form = formset.forms[i]

is much better written as this:

    for form in formset.forms:

and if for some reason you really did need that index variable, this is still better:

    for i, form in enumerate(formset.forms):
Daniel Roseman