ZCox
ZCox

Reputation: 89

Django - Save poll selected choices (not number of votes) in different classes of models

I'm facing difficulties in saving the selected choices of polls in different classes.

For example, I create questions and choices, and they are linked to each other (as from the tutorial of Django). In this tutorial, each time participants choose an answer, the selected choice is save as the number of vote (code given: selected_choice.votes += 1). I want to do more than that which is to save the whole answer, not just number.

This is code of saving number of votes:

def vote(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'polls/detail.html', {
            'question': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))

I also create another class Fill which require participant filling some information before they do the polls. What I want is the selected choices are also saved in this class of models. The pictures will describe what I'm trying to explain. Red circle in the 1s picture is where the selected choices are aimed to save. Red circle in the 2nd picture are number of votes saved.

enter image description here

enter image description here

This is the code of Q1, Q2, Q3 created in CharField type to store selected choices.

class Fill(models.Model):
    Q1 = models.CharField(max_length=200, default='')
    Q2 = models.CharField(max_length=200, default='')
    Q3 = models.CharField(max_length=200, default='')

I would really appreciate if anyone can help me out. Thank you.

P/s: My general idea is to save selected choices in the same list of personal data collected in order to know the selection of each person as describe in the 1st picture. So if you know any other ways rather then doing them in different classes then please enlighten me.

Upvotes: 0

Views: 1016

Answers (1)

MD Islam
MD Islam

Reputation: 137

You need to keep track of each user (maybe using request.user) as a ForeignKey in your model and have whatever other fields you want in the model. This way, each response is tied to a user.

https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey

Upvotes: 2

Related Questions