Commit cf8ef300 authored by christophe siraut's avatar christophe siraut

Main django application

parent 1061e5cc
from django import forms
from models import Poll, Choice, Bulletin, Vote
class PollForm(forms.ModelForm):
description = forms.CharField(widget=forms.Textarea)
class Meta:
model = Poll
fields = ('title','description')
class ChoiceForm(forms.ModelForm):
choice = forms.CharField(widget=forms.TextInput(attrs={'class':'hasdatepicker','size':'10',}))
details = forms.CharField(required=False,widget=forms.TextInput(attrs={'size':'32',}))
class Meta:
model = Choice
exclude = ('poll','votecount')
class BulletinForm(forms.ModelForm):
class Meta:
model = Bulletin
class VoteForm(forms.ModelForm):
comment = forms.CharField(required=False,widget=forms.TextInput(attrs={'class':'comment'}))
choice = forms.CharField()
voter = forms.CharField(required=False)
class Meta:
model = Vote
fields = ('choice','voice','comment')
from django.db import models
import os
from binascii import hexlify
def _createId():
# Generate a 4 caracters id
return hexlify(os.urandom(2))
class Poll(models.Model):
# Override django id AutoField with randomly generatyed hash
id = models.CharField(primary_key=True,unique=True,max_length=8,default=_createId)
title = models.CharField('Question',max_length=50)
pub_date = models.DateField('date published',auto_now_add=True)
upd_date = models.DateField('date updated',auto_now=True)
author = models.CharField(max_length=20)
description = models.CharField(max_length=200)
#public = models.BooleanField()
def __unicode__(self):
return self.title
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=20)
details = models.CharField(max_length=30,blank=True)
votecount = models.IntegerField(default=0,blank=True)
def __unicode__(self):
return self.choice
class Bulletin(models.Model):
poll = models.ForeignKey(Poll,editable=False)
voter = models.CharField("",max_length=20)
def __unicode__(self):
return self.voter
class Vote(models.Model):
choice = models.ForeignKey(Choice)
bulletin = models.ForeignKey(Bulletin)
voice = models.BooleanField(blank=True)
comment = models.CharField(max_length=30,blank=True)
def __unicode__(self):
return self.voice
"""
# First, define the Manager subclass.
class VoteBuletin(models.Manager):
def get_query_set(self):
return super(VoteBuletin, self).get_query_set().filter(author='Roald Dahl')
"""
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.failUnlessEqual(1 + 1, 2)
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
# Here are the views for nuage.sondage
import datetime
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render_to_response
from django.core.urlresolvers import reverse
#from django.template import Context, loader, RequestContext
from django.template import RequestContext
from django.forms.formsets import formset_factory
from django.forms.models import inlineformset_factory, BaseInlineFormSet
from nuage.sondage.models import Poll, Choice, Vote, Bulletin
from nuage.sondage.forms import PollForm, ChoiceForm, VoteForm, BulletinForm
from django.views.generic.create_update import update_object
from django.contrib.auth.decorators import login_required
def new(request):
if request.method == 'POST': # If the form has been submitted...
instance = Poll(author=str(request.user))
form = PollForm(request.POST, instance=instance) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
poll_id = form.cleaned_data.get('title') # Process the data in form.cleaned_data
new_poll = form.save()
#if not request.user.is_authenticated(): # Anonymous wants to create a poll...
key = 'is_' + new_poll.id + '_author'
request.session[key] = True # This writes cookie
redir = '/' + str(new_poll.id) + '/edit/choices/'
return HttpResponseRedirect(redir)
else:
form = PollForm() # An unbound form
return render_to_response('sondage/poll_form.html', {'form': form}, context_instance=RequestContext(request))
@login_required
def secure_update_object(*args, **kwargs):
"""
Souldn't we provide a better object to the generic view: object_id=poll
and then simple the template
# joe = str(request.user)
# if Poll.objects.get(id=object_id, author=joe):
"""
return update_object(*args, **kwargs)
def get_ordereditem_formset(form, formset=BaseInlineFormSet, **kwargs):
return inlineformset_factory(Poll, Choice, form, formset, **kwargs)
def editchoices(request, poll_id):
poll = get_object_or_404(Poll.objects.all(),id=poll_id)
if poll.author == 'AnonymousUser': # Anonymous wants to edit his new poll
key = 'is_' + poll_id + '_author'
if not request.session.get(key, False):
return HttpResponse('')
else:
if request.user.is_anonymous():
return HttpResponse('')
if request.user.username != poll.author:
return HttpResponse('')
OrderedItemFormset = get_ordereditem_formset(ChoiceForm, extra=0, can_delete=True)
if request.method == "POST":
"""
Should we set a maximum of choices here?
#instances = request.POST.values()
if len(instances) < 20:
for selection in instances:
"""
instances = OrderedItemFormset(request.POST, instance=poll)
if instances.is_valid():
for instance in instances.cleaned_data:
try:
this_choice = instance['choice']
if not instance.get('DELETE'):
try:
choice = Choice.objects.get(poll=poll,choice=instance['choice'])
choice.details = instance['details']
choice.save()
except (KeyError, Choice.DoesNotExist):
choice = Choice(poll=poll, choice=instance['choice'], details=instance['details'])
choice.save()
else:
try:
choice = Choice.objects.get(poll=poll,choice=this_choice)
"""
Removing a Choice will remove all childeren Vote objects.
When Django deletes an object, it emulates the behavior of
the SQL constraint ON DELETE CASCADE -- in other words, any
objects which had foreign keys pointing at the object to be
deleted will be deleted along with it."""
choice.delete()
except:
pass
except:
pass
#error_message = "Choices saved successfully."
redir = '/' + str(poll.id) + '/'
return HttpResponseRedirect(redir)
else:
#return HttpResponse(instances)
vforms=OrderedItemFormset(request.POST, instance=poll)
return render_to_response('sondage/choice_form.html', {'error_message' : instances.errors,'object': poll, 'vforms': vforms,}, context_instance=RequestContext(request))
if Choice.objects.filter(poll=poll_id).count() == 0:
# Sall we replace next line with something like OrderedItemFormset(extra=2)
OrderedItemFormset = get_ordereditem_formset(ChoiceForm, extra=2, can_delete=True)
vforms = OrderedItemFormset()
else:
vforms = OrderedItemFormset(instance=poll)
return render_to_response('sondage/choice_form.html', {'object': poll, 'vforms': vforms,}, context_instance=RequestContext(request))
def make_buletin_form(poll, **kwargs):
return [ [VoteForm(prefix=choice) ] for choice in Choice.objects.filter(poll=poll.id) ]
def vote(request, poll_id):
error_message = None
poll = get_object_or_404(Poll.objects.all(),id=poll_id)
if request.method == 'POST':
form = BulletinForm(request.POST,initial={'poll': poll.id,})
vforms = [ [VoteForm(request.POST, prefix=choice) ] for choice in Choice.objects.filter(poll=poll.id) ]
if form.is_valid():
if request.user.is_authenticated():
voter = str(request.user)
else:
voter = form.cleaned_data['voter']
if request.session.get('name'):
voter = request.session.get('name')
if voter != 'your name':
"""
try:
Bulletin.objects.get(poll=poll.id,voter=voter)
error_message = 'A user with the same name has already voted.'
return render_to_response('sondage/poll_detail.html', {'object': poll, 'form': form, 'vforms':vforms, 'error_message':error_message}, context_instance=RequestContext(request))
except:
pass
"""
if not Bulletin.objects.filter(poll=poll.id,voter=voter):
bulletin = Bulletin(poll=poll,voter=voter)
bulletin.save()
else:
bulletin = Bulletin.objects.get(poll=poll.id,voter=voter)
for forms in vforms:
for vorm in forms:
if vorm.is_valid():
try:
choice = Choice.objects.get(choice=vorm.cleaned_data['choice'],poll=poll)
except:
return HttpResponse("")
if not Vote.objects.filter(choice=choice,bulletin=bulletin):
vorm.cleaned_data['choice'] = choice
new = vorm.save(commit=False)
new.bulletin = bulletin
#new.choice = choice
new.save()
if new.voice:
choice.votecount += 1
choice.save()
error_message = "Your vote has been counted, thank you."
if request.user.is_anonymous(): # Anonymous has voted...
key = 'has_voted-' + poll.id
request.session[key] = True # This writes cookie
request.session['name'] = voter # This writes cookie
else:
old = Vote.objects.get(choice=choice,bulletin=bulletin)
if old.voice:
if not vorm.cleaned_data['voice']:
choice.votecount -= 1
choice.save()
else:
if vorm.cleaned_data['voice']:
choice.votecount += 1
choice.save()
old.voice = vorm.cleaned_data['voice']
old.comment = vorm.cleaned_data['comment']
old.save()
error_message = "Your vote has been updated, thank you."
else:
error_message = 'Did you forget to provide your name?'
else:
#error_message = form.errors
error_message = 'Did you forget to provide your name?'
voter = 'your name'
else: # request.method = 'GET'
key = 'is_' + poll.id + '_author'
if request.session.get(key, False):
# Assume author is positive for all choices, when he votes for the first time.
vforms = [ [ VoteForm(initial={'choice': choice,'voice': True,}, prefix=choice) ] for choice in Choice.objects.filter(poll=poll_id) ]
else:
# Default formset for unknown user
vforms = [ [ VoteForm(initial={'choice': choice,}, prefix=choice) ] for choice in Choice.objects.filter(poll=poll_id) ]
if request.user.is_authenticated():
voter = str(request.user)
try:
bulletin = Bulletin.objects.get(poll=poll,voter=voter)
error_message = " you have voted."
diff = len(vforms) - len(Vote.objects.filter(bulletin=bulletin))
if diff == 0:
"""
Hum, previously bulletin has not the same amount of vote objects,
we should concatenate the existing votes with empty remaing ones...
Give an empty bulletin for now.
"""
vforms = [ [ VoteForm(initial={'choice': vote.choice,'voice': vote.voice, 'comment': vote.comment,}, prefix=vote.choice) ] for vote in Vote.objects.filter(bulletin=bulletin) ]
except:
pass
else:
voter = 'your name'
error_message = "Login let you modify your vote anytime."
key = 'has_voted-' + poll.id
if request.session.get(key, False):
voter = request.session.get('name')
#error_message = 'Modify your vote? (clear cookie if you are not ' + voter + ')'
try:
bulletin = Bulletin.objects.get(poll=poll,voter=voter)
error_message = ' you have voted, clear cookie if you are not ' + voter
diff = len(vforms) - len(Vote.objects.filter(bulletin=bulletin))
if diff == 0:
"""
Hum, previously bulletin has not the same amount of vote objects,
we should concatenate the existing votes with empty remaing ones...
Give an empty bulletin for now.
"""
vforms = [ [ VoteForm(initial={'choice': vote.choice,'voice': vote.voice, 'comment': vote.comment,}, prefix=vote.choice) ] for vote in Vote.objects.filter(bulletin=bulletin) ]
except:
pass
form = BulletinForm(instance=poll,initial={'voter': voter})
return render_to_response('sondage/poll_detail.html', {'object': poll, 'form': form, 'vforms':vforms, 'error_message':error_message}, context_instance=RequestContext(request))
from django.db import models
# Create your models here.
"""
This file demonstrates two different styles of tests (one doctest and one
unittest). These will both pass when you run "manage.py test".
Replace these with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.failUnlessEqual(1 + 1, 2)
__test__ = {"doctest": """
Another way to test that 1 + 1 is equal to 2.
>>> 1 + 1 == 2
True
"""}
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
return HttpResponseRedirect("/user/login/")
else:
form = UserCreationForm()
return render_to_response("registration/register.html", {
'form': form,
}, context_instance=RequestContext(request))
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment