[Solved]-How to make a customizable user survey in Django

5πŸ‘

βœ…

I think your models are fine. I used the Django admin to create an EvaluationScheme with EvaluationQuestions, then I created an Evaluation and I was able to answer its questions. Here’s the code I used to go with your models:

# forms.py:
from django.forms.models import inlineformset_factory
import models

AnswerFormSet = inlineformset_factory(models.Evaluation, 
        models.EvaluationAnswer, exclude=('question',), 
        extra=0, can_delete=False)

# views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
import models, forms

def prepare_blank_answers(evaluation):
    for question in evaluation.scheme.evaluationquestion_set.all():
        answer = models.EvaluationAnswer(evaluation=evaluation,
                                         question=question)
        answer.save()

def answer_form(request, id):
    evaluation = get_object_or_404(models.Evaluation, id=id)
    if len(evaluation.evaluationanswer_set.all()) == 0:
        prepare_blank_answers(evaluation)
    if request.method == 'POST':
        formset = forms.AnswerFormSet(request.POST, instance=evaluation)
        if formset.is_valid():
            formset.save()
            return HttpResponse('Thank you!')
    else:
        formset = forms.AnswerFormSet(instance=evaluation)
    return render_to_response('answer_form.html',
            {'formset':formset, 'evaluation':evaluation})


# answer_form.html:
<html><head></head><body>
  Doctor: {{ evaluation.doctor }} <br>
  Agency: {{ evaluation.agency }}
  <form method="POST">
    {{ formset.management_form }}
    <table>
      {% for form in formset.forms %}
        <tr><th colspan="2">{{ form.instance.question }}</th></tr>
        {{ form }}
      {% endfor %}
    </table>
    <input type="submit">
  </form>
</body></html>
πŸ‘€krubo

4πŸ‘

Have you checked django-survey? It’s pretty neat.

πŸ‘€Arnaud

3πŸ‘

Django-crowdsourcing is a fork of django-survey that is actively maintained as of 2012 and targets Django 1.2+.

πŸ‘€Bayard Randel

1πŸ‘

Not a django expert so you might wish to wait for a more experience person to answer but you could try something like:

EvaluationQuestions.objects.filter(evaluationscheme__title="myscheme").select_related()

Could also put the relationships the other way around, depends how you need to access the data.

class EvaluationScheme(models.Model):
    title = models.CharField(max_length=200)
    evaluations = models.ManyToMany(Evaluation)
    questions = models.ManyToMany(EvaluationQuestions)
πŸ‘€PhoebeB

Leave a comment