如何使用django formsets进行问卷调查

时间:2013-11-25 23:26:08

标签: python django django-forms formsets

我正在做一个应用程序,现在我需要做一个用户可以进行的评估,我的问题是我想使用一个formset来列出各个选项的问题,我知道这可以通过使用formset来完成不是完成它的方法。以下是我的代码:

# models.py

class Evaluation(models.Model):
    """
    An evaluation is for a session.
    Each session should have an evaluation
    """
    session = models.OneToOneField(
        Session,
        related_name='evaluation',
        verbose_name=u'Sesión'
    )

    class Meta:
        verbose_name = u'Evaluación'
        verbose_name_plural = u'Evaluaciones'

    def __unicode__(self):
        return u'Evaluación de la sesion {0}'.format(
            self.session.name
        )


class Question(models.Model):
    """
    A question inside of an evaluation
    """
    evaluation = models.ForeignKey(
        Evaluation,
        verbose_name=u'Evaluación',
        related_name='questions'
    )
    question_type = models.CharField(
        max_length=20,
        verbose_name=u'Tipo de respuesta',
        choices=QUESTION_TYPES
    )
    sentence = models.CharField(
        max_length=255,
        verbose_name=u'Pregunta'
    )
    position = models.IntegerField(
        default=0,
        verbose_name=u'Posición'
    )

    class Meta:
        verbose_name = u'Pregunta'
        verbose_name_plural = u'Preguntas'
        ordering = ['position', 'sentence']

    def __unicode__(self):
        return self.sentence


class Choice(models.Model):
    question = models.ForeignKey(
        Question,
        related_name='choices',
        verbose_name=u'Pregunta'
    )
    sentence = models.CharField(
        max_length=255,
        verbose_name=u'Posible respuesta'
    )
    position = models.IntegerField(
        default=0,
        verbose_name=u'Posición'
    )

    class Meta:
        verbose_name = u'Posible respuesta'
        verbose_name_plural = u'Posibles respuestas'
        ordering = ['position', 'sentence']

    def __unicode__(self):
        return self.sentence

----

# forms.py

from django.forms.models import inlineformset_factory
from models import Evaluation, Question


AnswerFormSet = inlineformset_factory(
    Evaluation, Question, exclude=('question',),
    extra=0, can_delete=False
)

----

# views.py

@login_required()
def session_evaluation(request, course_slug, session_position):
    data = {}
    course = get_object_or_404(Course, slug=course_slug)
    session = Session.objects.filter(course=course).get(position=session_position)
    evaluation = get_object_or_404(Evaluation, session=session)
    if request.method == 'POST':
        formset = AnswerFormSet(request.POST, instance=evaluation)
        if formset.is_valid():
            formset.save()
            print 'formset valid...'
    else:
        formset = AnswerFormSet(instance=evaluation)
    data['course'] = course
    data['session'] = session
    data['formset'] = formset
    return render(request, 'courses/session_evaluation.html', data)

----

# template.html
<form id="evaluation" method="post" role="form">
    {% csrf_token %}
    {{ formset.management_form }}
    <ul class="evaluation">
        {% for form in formset.forms %}
            <li>
                {{ form.instance }}
                {{ form.instance.choices.all }}
            </li>
        {% endfor %}
    </ul>
    <div class="form-group clearfix nmb">
        <button type="submit" class="btn btn-primary pull-right">Enviar respuestas</button>
    </div>
</form>

正如你所看到的,我已经很好地编写了模型但是从表格中可以看出所有代码只是一个实验而且我真的不知道如何做到这一点。

我在模板中使用此代码获得的是问题句子和选择列表,例如:

[question sentence here]? [<Choice: [choice #1 here]>, <Choice: [choice #2 here]>] 

使用formset执行此操作的简洁方法是什么?

我想得到的是带有单选按钮的相应选项列表的问题列表,因为这是一个评估。

1 个答案:

答案 0 :(得分:0)

不应该是{{ form.as_p }}{{ form.as_table }}吗?该实例已在视图中创建,因此无需在模板中使用。