使用清理数据形成错误

时间:2017-10-02 11:21:48

标签: django django-models django-forms

我正在尝试修改我在网上找到的应用程序,以便创建调查但我收到的错误是我无法解决

form.py:

   def save(self, commit=True):
        import pdb; pdb.set_trace()
        """ Save the response object """
        # Recover an existing response from the database if any
        #  There is only one response by logged user.
        response = self._get_preexisting_response()
        if response is None:
            response = super(ResponseForm, self).save(commit=False)
        response.survey = self.survey
        response.interview_uuid = self.uuid
        if self.user.is_authenticated():
            response.user = self.user
        response.save()
        # response "raw" data as dict (for signal)
        data = {
            'survey_id': response.survey.id,
            'interview_uuid': response.interview_uuid,
            'responses': []
        }
        # create an answer object for each question and associate it with this
        # response.
        for field_name, field_value in self.cleaned_data.items():
            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])
                question = Question.objects.get(pk=q_id)
                answer = self._get_preexisting_answer(question)
                if answer is None:
                    answer = Answer(question=question)
                if question.type == Question.SELECT_IMAGE:
                    value, img_src = field_value.split(":", 1)
                    # TODO
                answer.body = field_value
                data['responses'].append((answer.question.id, answer.body))
                LOGGER.debug(
                    "Creating answer for question %d of type %s : %s", q_id,
                    answer.question.type, field_value
                )
                answer.response = response
                answer.save()
        survey_completed.send(sender=Response, instance=response, data=data)
        return response

views.py

class SurveyDetail(View):
    #import pdb; pdb.set_trace()
    def get(self, request, *args, **kwargs):
        survey = get_object_or_404(Survey, is_published=True, id=kwargs['id'])
        if survey.template is not None and len(survey.template) > 4:
            template_name = survey.template
        else:
            if survey.display_by_question:
                template_name = 'survey/survey.html'
            else:
                template_name = 'survey/one_page_survey.html'
        if survey.need_logged_user and not request.user.is_authenticated():
            return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
        categories = Category.objects.filter(survey=survey).order_by('order')
        form = ResponseForm(survey=survey, user=request.user,
                            step=kwargs.get('step', 0))
        context = {
            'response_form': form,
            'survey': survey,
            'categories': categories,
        }

        return render(request, template_name, context)

    def post(self, request, *args, **kwargs):
        import pdb; pdb.set_trace()
        survey = get_object_or_404(Survey, is_published=True, id=kwargs['id'])
        if survey.need_logged_user and not request.user.is_authenticated():
            return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
        categories = Category.objects.filter(survey=survey).order_by('order')
        form = ResponseForm(request.POST, survey=survey, user=request.user,
                            step=kwargs.get('step', 0))
        context = {'response_form': form, 'survey': survey,
                   'categories': categories}
        if form.is_valid():
            session_key = 'survey_%s' % (kwargs['id'],)
            if session_key not in request.session:
                request.session[session_key] = {}
            for key, value in form.cleaned_data.items():
                request.session[session_key][key] = value
                request.session.modified = True

            next_url = form.next_step_url()
            response = None
            if survey.display_by_question:
                if form.has_next_step():
                    save_form = ResponseForm(request.session[session_key],
                                             survey=survey, user=request.user)
                    response = save_form.save(request)
            else:
                response = form.save()

            if next_url is not None:
                return redirect(next_url)
            else:
                del request.session[session_key]
                if response is None:
                    return redirect('/')
                else:
                    next_ = request.session.get('next', None)
                    if next_ is not None:
                        if 'next' in request.session:
                            del request.session['next']
                        return redirect(next_)
                    else:
                        return redirect('survey-confirmation',
                                        uuid=response.interview_uuid)
        if survey.template is not None and len(survey.template) > 4:
            template_name = survey.template
        else:
            if survey.display_by_question:
                template_name = 'survey/survey.html'
            else:
                template_name = 'survey/one_page_survey.html'
        return render(request, template_name, context)

我们得到的错误就是我得到了错误AttributeError:'ResponseForm'对象没有属性'cleaning_data',即使表单得到了is_valid属性

1 个答案:

答案 0 :(得分:1)

.cleaned_data仅在您在表单上调用.is_valid()后才可用。

您很可能还未在视图中的表单上调用is_valid()