更改模型后,ModelForm save()不起作用

时间:2014-01-07 15:00:39

标签: django django-forms

我正在玩jessykate(https://github.com/jessykate/django-survey)的django调查,并改变了models.py。现在save()方法不再起作用了,我不明白为什么会这样。

models.py(见评论#)

class Response(models.Model):
    '''
    a response object is just a collection of questions and answers with a
    unique interview uuid
    '''
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    survey = models.ForeignKey(Survey)
    # interviewer = models.CharField('Name of Interviewer', max_length=400)
    # interviewee = models.CharField('Name of Interviewee', max_length=400)
    # conditions = models.TextField('Conditions during interview', blank=True, null=True)
    # comments = models.TextField('Any additional Comments', blank=True, null=True)
    interview_uuid = models.CharField("Interview unique identifier", max_length=36)

    def __unicode__(self):
        return ("response %s" % self.interview_uuid)

views.py(原创)

def SurveyDetail(request, id):
    survey = Survey.objects.get(id=id)
    category_items = Category.objects.filter(survey=survey)
    categories = [c.name for c in category_items]
    print 'categories for this survey:'
    print categories
    if request.method == 'POST':
        form = ResponseForm(request.POST, survey=survey)
        if form.is_valid():
            response = form.save()
            return HttpResponseRedirect("/confirm/%s" % response.interview_uuid)
    else:
        form = ResponseForm(survey=survey)
        print form
        # TODO sort by category
    return render(request, 'survey.html', {'response_form': form, 'survey': survey, 'categories': categories})

forms.py(见评论#)

class ResponseForm(models.ModelForm):
    class Meta:
        model = Response    
    #   fields = ('interviewer', 'interviewee', 'conditions', 'comments')

[...]

def save(self, commit=True):
        ''' save the response object '''
        response = super(ResponseForm, self).save(commit=False)
        response.survey = self.survey
        response.interview_uuid = self.uuid
        response.save()

        '''
            create an answer object for each question and associate it with this 
            response.
            '''
        for field_name, field_value in self.cleaned_data.iteritems():
            if field_name.startswith("question_"):
                # warning: this way of extracting the id is very fragile and
                # entirely dependent on the way the question_id is encoded in the
                # field name in the __init__ method of this form class.
                q_id = int(field_name.split("_")[1])
                q = Question.objects.get(pk=q_id)

                if q.question_type == Question.TEXT:
                    a = AnswerText(question = q)
                    a.body = field_value
                elif q.question_type == Question.RADIO:
                    a = AnswerRadio(question = q)   
                    a.body = field_value
                elif q.question_type == Question.SELECT:
                    a = AnswerSelect(question = q)  
                    a.body = field_value
                elif q.question_type == Question.SELECT_MULTIPLE:
                    a = AnswerSelectMultiple(question = q)  
                    a.body = field_value
                elif q.question_type == Question.INTEGER:   
                    a = AnswerInteger(question = q) 
                    a.body = field_value
                print "creating answer to question %d of type %s" % (q_id, a.question.question_type) 
                print a.question.text
                print 'answer value:'
                print field_value
                a.response = response
                a.save()
        return response

所以当我保存调查时,我将获得完全相同的页面,而不是确认页面。

任何线索?

1 个答案:

答案 0 :(得分:0)

您目前正在修改项目中的第三方代码。你面临的困难是一个快速的教训(我们都学习)为什么这是一个坏主意™。从查看代码开始,您似乎只想从Response模型中删除一些字段。解决该问题的更好方法是编写自己的MyResponse模型并使用它,而不是编辑第三方应用程序的来源。

如果您坚持使用您的修改(不要坚持使用您的修改),那么您需要确定form.is_valid()False的原因(这是猜测,“save()isn”工作“非常模糊,但你没有发布错误追溯,所以我假设没有一个)。您的表单中存在错误,如果您访问它们:

for field, errors in form.errors.items():
    print field
    for error in errors:
        print error

然后他们会让你更好地了解正在发生的事情。

编辑:根据您发布的错误,您可以看到问题出在哪里,当表单缺少form.is_valid()属性时,您正在调用survey,因此is_valid()评估为False,你的表单的save()方法甚至都不会被调用。在致电form.survey = survey之前设置form.is_valid(),看看会发生什么。