0

I would like to display a question and have the user rate it from 1-5 as a poll. Five radio buttons. I have the question generated but I'm not sure how to go about creating the 5 options for the user.

The goal would be to export the question and rating to a csv file every time the user votes on it by clicking on a submit button (after selecting a choice). It needs to write-out the question and the selected rating (1, 2, 3, 4, or 5) to the file. I need some help getting started on this.

rantanplan
  • 7,283
  • 1
  • 24
  • 45
ono
  • 2,984
  • 9
  • 43
  • 85
  • doesn't django have a poll tutorial? I think it includes something very similar to what you are trying to do.. – Joran Beasley Oct 02 '12 at 18:29
  • Yes but I'm interested in writing out the selected choice, not summing up the number of times each is selected. – ono Oct 02 '12 at 19:53

2 Answers2

0

Here's the general idea to write to a file. Replace 'A', 'B', 'C' with your data.

Perhaps it comes from a form, request.POST['selected_choice'], etc.

import csv

with open('foo.csv', 'ab') as f:
    writer = csv.writer(f)
    writer.writerow(['A', 'B', 'C'])
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
0
from django import forms
from django.forms import ModelForm
from django.db import models

class Poll(models.Model):
    RATING_CHOICES = [(i,i) for i in range(1,6)]
    question = models.TextField()
    rating = models.PositiveSmallIntegerField(choices=RATING_CHOICES)


class PollForm(ModelForm):
    class Meta:
        model = Poll
        fields = ('question', 'rating')
        widgets = {'rating': forms.RadioSelect}

In your views, you'll have something like:

import csv

from django.http import render_to_response, HttpResponseRedirect
from myproject.forms import PollForm

def myview(request):
    context = {}
    if request.method == 'POST'
        form = PollForm(request.POST)
        if form.is_valid():
            obj = form.save()
            with open('foo.csv', 'ab') as f:  # Shamelessly stolen from Yuji
                writer = csv.writer(f)
                writer.writerow([obj.question, obj.rating])
            return HttpResponseRedirect('somesuccesspage')
    # More boring code here to handle the GET requests and stuff..
    context['form'] = form
    return render_to_response('somepath/mytempplate.html', context)

Haven't run the above code, but it surely is something to get you started.

rantanplan
  • 7,283
  • 1
  • 24
  • 45
  • Thanks. Importing PollForm doesn't work for some reason. I get the error 'No module named forms' – ono Oct 03 '12 at 15:51
  • @ono3 did you do the `from django import forms` which is the first line in my code? But anyway keep in mind that the PollForm should live in a different module, like `forms.py`. Start with this code(hand in hand with the django docs) and if you come across any other problems post a separate question. – rantanplan Oct 03 '12 at 20:39