Django Post Request with custom Dict for Dynamic Survey

时间:2013-09-12 19:25:17

标签: python django forms django-forms

我有以下结构:

class Question(models.Model):
    survey = models.ForeignKey('Survey')
    text = models.CharField(max_length=255, default="")

class Answer(models.Model):
    user = models.ForeignKey('User')
    text = models.CharField(max_length=255, default="")

并生成表单。 enter image description here

我的问题是......我如何获取POST数据?

我试试:

{% for question in survey %}
    <div class="control-group ">
        <label class="control-label" for="{{question.id}}" >{{question.id}}</label>
        <div class="controls">
            <input type="text" value="{{question|answer:user}}" class="grd-white" name="answer" id="answer_{{question.id}}" />
        </div>
    </div>                                
{% endfor %}

但结果是:

enter image description here

我需要类似的东西:

{"answers":{id_question_1:"text_answer_1",id_question_2:"text_answer_2",id_question_3:"text_answer_3" }}

示例:

{"answers":{1:"A1",2:"A2",3:"a3"}}

1 个答案:

答案 0 :(得分:0)

这是我唯一能想到的:

模板

name="answer_{{question.id}}"

views.py

dict([(k.split('_')[-1], v) for (k, v) in request.POST.items() if 'answer' in k])