Django使用初始数据进行表单渲染

时间:2016-12-21 15:18:21

标签: python django forms

我有一个问题模型,并根据问题是多项选择还是文本输入来回答模型。

在我的观点中,我试图用初始数据渲染表单。初始数据将获得用户答案,如果它已经被回答并且它正常工作但是当出现问题时,用户没有给出答案,那么抛出RelatedObjectDoesNotExist异常并且它显示

“UserTextAnswer没有my_answer”,在模板中给出。

我的模特:

Question_Types_Choices = (
    ('multiple_choice', ('multiple_choice')),
    ('text_input', ('text_input'))
)

class Question(models.Model):
    text = models.TextField()
    active = models.BooleanField(default=True)
    question_type = models.CharField(max_length = 250, choices =Question_Types_Choices)
    timestamp = models.DateTimeField(auto_now_add=True , auto_now=False)



    def __unicode__(self):
        return self.text[:10]

class FreeTextAnswer(models.Model):
    answers = models.ForeignKey(Question)
    text = models.TextField(blank=True, null=True)
    active = models.BooleanField(default=True)
    timestamp = models.DateTimeField(auto_now_add=True , auto_now=False)

    def __unicode__(self):
        return self.text[:10]


class UserTextAnswer(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    question = models.ForeignKey(Question)  
    my_answer = models.ForeignKey(FreeTextAnswer)
    my_points = models.IntegerField(default=-1)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

    def __unicode__(self):
        return self.my_answer.text[:10]

在我看来:

def single(request,id):
    if request.user.is_authenticated():


        queryset = Question.objects.all().order_by('-timestamp')
        instance = get_object_or_404(Question, id=id)


        try:
            user_text_answer = UserTextAnswer.objects.get(user=request.user, question=instance)
        except UserTextAnswer.DoesNotExist:
            user_text_answer = UserTextAnswer()
        except UserTextAnswer.MultipleObjectsReturned:
            user_text_answer = UserTextAnswer.objects.filter(user=request.user, question=instance)[0]
        except:
            user_text_answer = UserTextAnswer()



        try:
            free_text_answer = FreeTextAnswer.objects.get(answers_id=instance.id)
        except FreeTextAnswer.DoesNotExist:
            free_text_answer = FreeTextAnswer()
        except FreeTextAnswer.MultipleObjectsReturned:
            free_text_answer = FreeTextAnswer.objects.filter(answers_id=instance.id)[0]
        except:
            free_text_answer = FreeTextAnswer()


        initial_dict = {
            "my_answer": user_text_answer
            }

        form2 = UserTextFreeForm(request.POST or None, initial = initial_dict)
        form = UserResponseForm(request.POST or None)


        if request.method == 'POST':


            if form2.is_valid():
                "process the form"

在我的模板中,我正在渲染它,

<form method='POST' action='{% url "question_single" id=instance.id%}' > {% csrf_token %}

<h1>{{ instance.text }}</h1>

<input type='hidden' name='question_id' value='{{ instance.id }}' />

<h3>Your answer</h3>

   {{ form2.my_answer.errors }}
    {{ form2.my_answer }}




<input type='submit' value='Save and continue' />

</form>

问题的初始词典应该是空的,但我试图检查它总是返回的长度。我也尝试捕获user_text_answer.DoesNotExist异常但不起作用。

我应该如何控制我的初始字典,这样当一个问题没有答案时,它会在没有数据的情况下正常加载,如果答案与答案相关联,那么它应该显示数据吗?

2 个答案:

答案 0 :(得分:0)

而不是get验证DoesNotExistMultipleObjectsReturned,您只需将filterfirst一起使用:

user_text_answer = UserTextAnswer.objects.filter(user=request.user, question=instance).first()

initial_dict = {}
if user_text_answer:
    initial_dict["my_answer"] = user_text_answer

答案 1 :(得分:0)

我弄清楚为什么初始字典返回值为1,即使它必须为空。我通过执行以下操作解决了这个问题:

try:
            user_text_answer = UserTextAnswer.objects.get(user=request.user, question=instance)
            initial_dict = {
            "my_answer": user_text_answer
            }
        except UserTextAnswer.DoesNotExist:
            user_text_answer = UserTextAnswer()
            initial_dict = {

            }
        except UserTextAnswer.MultipleObjectsReturned:
            user_text_answer = UserTextAnswer.objects.filter(user=request.user, question=instance)[0]
            initial_dict = {
            "my_answer": user_text_answer
            }
        except:
            user_text_answer = UserTextAnswer()
            initial_dict = {

            }

应根据try和except块内的情况进行初始化,而不是之后。