Commits

RafRaf committed a2e586a

*Refactoring* The new version have some incompatibilities with older releases. Please, remove old version before installing it.

Comments (0)

Files changed (11)

-# file GENERATED by distutils, do NOT edit
-README.txt
-setup.py
-poll\__init__.py
-poll\admin.py
-poll\ajax.py
-poll\models.py
-poll\urls.py
-poll\utils.py
-poll\fixtures\initial_data.json
-poll\locale\ru\LC_MESSAGES\django.mo
-poll\locale\ru\LC_MESSAGES\django.po
-poll\static\polls\css\polls.css
-poll\static\polls\js\common.js
-poll\templates\polls.html
-poll\templatetags\__init__.py
-poll\templatetags\polls_tags.py
+# file GENERATED by distutils, do NOT edit
+README.txt
+setup.py
+poll/__init__.py
+poll/admin.py
+poll/ajax.py
+poll/models.py
+poll/urls.py
+poll/utils.py
+poll/fixtures/initial_data.json
+poll/locale/ru/LC_MESSAGES/django.mo
+poll/locale/ru/LC_MESSAGES/django.po
+poll/templates/_polls_script.js
+poll/templates/_polls_style.css
+poll/templates/polls.html
+poll/templatetags/__init__.py
+poll/templatetags/polls_tags.py
 from django.contrib import admin
-from poll.models import PollType, Poll, Item, Queue, Vote, Choice
+from poll.models import Poll, Item, Queue, Vote, Choice
 from django.utils.translation import gettext as _
 
 class PollItemInline(admin.TabularInline):
     max_num = 10
 
 class PollAdmin(admin.ModelAdmin):
-    list_display = ('publish', 'queue', 'startdate', 'polltype', 'title', 'vote_count')
+    list_display = ('title', 'queue', 'startdate', 'polltype', 'vote_count', 'publish')
     
     inlines = [
         PollItemInline,
     ]
 
 admin.site.register(Poll, PollAdmin)
-admin.site.register(PollType, admin.ModelAdmin)
 admin.site.register(Queue, admin.ModelAdmin)
 admin.site.register(Vote, VoteAdmin)
-
-#admin.site.register(Item, admin.ModelAdmin)
-#admin.site.register(Choice, admin.ModelAdmin)
 from django.http import HttpResponse
 from poll.models import Poll, Item, Vote, Choice
 from django.db import transaction
-from django.contrib.auth.models import AnonymousUser
 from django.utils import simplejson
 from utils import set_cookie
 
-def authpassQueue(user, queue):
+def authpass(user, queue):
     if queue != None:
-        if queue.auth and not user.has_perm('Poll.can_vote'):
-            return False
+        if queue.auth:
+            if not user.is_authenticated():
+                return False
     return True
 
 #TODO: Need to optimize
 @transaction.commit_on_success
 def poll_ajax_vote(request, poll_pk):
     if request.is_ajax():
-        
-        queue = Poll.publish_manager.get(pk=poll_pk).queue
-        if not authpassQueue(request.user, queue):    
-            return HttpResponse(status=400)
-        
         try:
+            poll = Poll.objects.get(pk=poll_pk)
+            
+            if poll.queue:
+                if not authpass(request.user, poll.queue):
+                    return HttpResponse('Non-authenticated users can\'t vote', status=400)
+            
             chosen_items = simplejson.loads(request.GET['chosen_items'])
         except:
-            return HttpResponse(status=400)
+            return HttpResponse('Wrong parameters', status=400)
         
-        poll = Poll.objects.get(pk=poll_pk)
-        
-        if isinstance(request.user, AnonymousUser):
+        if request.user.is_authenticated():
+            user = request.user
+        else:
             user = None
-        else:
-            user = request.user 
         
         vote = Vote.objects.create(poll=poll,
                                    ip=request.META['REMOTE_ADDR'],
                                    user=user)
-        
-        for item_pk, value in chosen_items.items():
-            item = Item.objects.get(pk=item_pk)
-            
-            if item.userbox:
-                Choice.objects.create(vote=vote, item=item, uservalue=value)
-            else:
-                Choice.objects.create(vote=vote, item=item)
+        try:
+            for item_pk, value in chosen_items.items():
+                item = Item.objects.get(pk=item_pk)
+                
+                if item.userbox:
+                    Choice.objects.create(vote=vote, item=item, uservalue=value)
+                else:
+                    Choice.objects.create(vote=vote, item=item)
+        except:
+            return HttpResponse('Data recognition failed', status=400)
         
         response = HttpResponse(status=200)
         set_cookie(response, poll.get_cookie_name(), poll_pk)
 
 def poll_ajax_result(request, poll_pk):
     if request.is_ajax():
-        poll = Poll.objects.get(pk=poll_pk)        
+        try:
+            poll = Poll.objects.get(pk=poll_pk)
+        except:
+            return HttpResponse('Wrong parameters', status=400)
+        
         #Send data for results
         data = {}
         

poll/fixtures/initial_data.json

-[{"pk": 2, "model": "poll.polltype", "fields": {"index": 1, "title": "Multiple"}}, {"pk": 1, "model": "poll.polltype", "fields": {"index": 0, "title": "Single"}}, {"pk": 1, "model": "poll.poll", "fields": {"startdate": "2011-11-06", "votes": [], "title": "Who will be a next Russian President?", "publish": true, "polltype": 1, "queue": 1}}, {"pk": 1, "model": "poll.queue", "fields": {"auth": false, "title": "Public"}}, {"pk": 2, "model": "poll.queue", "fields": {"auth": true, "title": "Private"}}, {"pk": 1, "model": "poll.item", "fields": {"index": 0, "poll": 1, "value": "Mr. Medvedev", "userbox": false}}, {"pk": 2, "model": "poll.item", "fields": {"index": 1, "poll": 1, "value": "Mr. Putin", "userbox": false}}, {"pk": 3, "model": "poll.item", "fields": {"index": 2, "poll": 1, "value": "Mr. Freeman", "userbox": false}}, {"pk": 4, "model": "poll.item", "fields": {"index": 3, "poll": 1, "value": "KGB", "userbox": false}}, {"pk": 5, "model": "poll.item", "fields": {"index": 4, "poll": 1, "value": "or...", "userbox": true}}, {"pk": 1, "model": "poll.vote", "fields": {"ip": "127.0.0.1", "poll": 1, "user": 1, "datetime": "2011-11-06 09:04:01"}}, {"pk": 1, "model": "poll.choice", "fields": {"vote": 1, "item": 4, "uservalue": null}}]
+[{"pk": 1, "model": "poll.poll", "fields": {"startdate": "2012-02-04", "votes": [], "title": "How do you spend your free time?", "publish": true, "polltype": "0", "queue": 1}}, {"pk": 1, "model": "poll.queue", "fields": {"auth": false, "title": "Public"}}, {"pk": 2, "model": "poll.queue", "fields": {"auth": true, "title": "Private"}}, {"pk": 1, "model": "poll.item", "fields": {"index": 0, "poll": 1, "value": "I learn new technologies", "userbox": false}}, {"pk": 2, "model": "poll.item", "fields": {"index": 1, "poll": 1, "value": "I play computer games", "userbox": false}}, {"pk": 3, "model": "poll.item", "fields": {"index": 2, "poll": 1, "value": "I drink vodka and lie in my backyard", "userbox": false}}, {"pk": 4, "model": "poll.item", "fields": {"index": 3, "poll": 1, "value": "I don't have free time", "userbox": false}}, {"pk": 1, "model": "poll.vote", "fields": {"ip": "188.233.241.89", "poll": 1, "user": 1, "datetime": "2012-02-04 01:19:35"}}, {"pk": 1, "model": "poll.choice", "fields": {"vote": 1, "item": 3, "uservalue": null}}]

poll/locale/ru/LC_MESSAGES/django.mo

Binary file modified.

poll/locale/ru/LC_MESSAGES/django.po

 msgstr ""
 "Project-Id-Version: PACKAGE VERSION\n"
 "Report-Msgid-Bugs-To: \n"
-"POT-Creation-Date: 2012-01-05 12:10+0400\n"
+"POT-Creation-Date: 2012-02-03 13:41+0400\n"
 "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
 "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
 "Language-Team: LANGUAGE <LL@li.org>\n"
-"Language: \n"
 "MIME-Version: 1.0\n"
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
-"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n"
-"%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)\n"
+"Language: \n"
+"Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%"
+"10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)\n"
 
-#: admin.py:19
+#: .\admin.py:19
 msgid "Options"
 msgstr "Опции"
 
-#: models.py:8
-msgid "Type title"
-msgstr "Введите заголовок"
-
-#: models.py:8
-msgid "It will be used as header of the poll"
-msgstr "Будет использован как заголовок опроса"
-
-#: models.py:9
-msgid "Index"
-msgstr "Индекс"
-
-#: models.py:9 models.py:27
-msgid "Must be unique"
-msgstr "Должен быть уникальным"
-
-#: models.py:16
-msgid "PollType"
-msgstr "Тип опроса"
-
-#: models.py:17
-msgid "PollTypes"
-msgstr "Типы опроса"
-
-#: models.py:24
+#: .\models.py:17
 msgid "Title"
 msgstr "Заголовок"
 
-#: models.py:24
+#: .\models.py:17
 msgid "The parameter is used as question to user"
 msgstr "Параметр используется как заголовок вопроса к пользователю"
 
-#: models.py:25 models.py:76
+#: .\models.py:18 .\models.py:71
 msgid "Queue"
 msgstr "Очередь"
 
-#: models.py:25
+#: .\models.py:18
 msgid ""
 "Do you want to use the poll as a stand alone poll or insert it into the "
 "queue?"
 "Вы хотите использовать опрос как отдельностоящий опрос или вставить его в "
 "очередь?"
 
-#: models.py:26
+#: .\models.py:19
 msgid "Poll type"
 msgstr "Тип опроса"
 
-#: models.py:26
+#: .\models.py:19
 msgid "Choose the poll type"
 msgstr "Выберете тип опроса"
 
-#: models.py:27
+#: .\models.py:20
 msgid "Start date"
 msgstr "Дата старта"
 
-#: models.py:28
+#: .\models.py:20
+msgid "Must be unique"
+msgstr "Должен быть уникальным"
+
+#: .\models.py:21
 msgid "Publish"
 msgstr "Публиковать"
 
-#: models.py:29 models.py:105
+#: .\models.py:22 .\models.py:100
 msgid "Votes"
 msgstr "Голоса"
 
-#: models.py:29
+#: .\models.py:22
 msgid "Choose variants of answers"
 msgstr "Выберете варианты ответов"
 
-#: models.py:36
+#: .\models.py:29
 msgid "\"Start dates\" of polls in the same queue must be different"
 msgstr ""
 "Параметры \"Start dates\" у разных опросов в одной очереди должны быть "
 "отличны"
 
-#: models.py:58 models.py:92 templates/polls.html:133
+#: .\models.py:54 .\models.py:87 .\templates\polls.html.py:22
 msgid "Poll"
 msgstr "Опрос"
 
-#: models.py:59
+#: .\models.py:55
 msgid "Polls"
 msgstr "Опросы"
 
-#: models.py:60
-msgid "User can vote"
-msgstr "Пользователь может голосовать"
-
-#: models.py:63
+#: .\models.py:58
 msgid "Queue name"
 msgstr "Название очереди"
 
-#: models.py:63
+#: .\models.py:58
 msgid "It must be unique"
 msgstr "Должен быть уникальным"
 
-#: models.py:64
+#: .\models.py:59
 msgid "Need auth?"
 msgstr "Нужна аутентификация?"
 
-#: models.py:64
+#: .\models.py:59
 msgid ""
 "Do the poll queue is for authenticated users only or not? (If yes, users "
 "must have \"can_vote\" permission to vote)"
 "Очередь опросов только для аутентифицированных пользователей или нет? (Иначе "
 "у пользователя должен быть доступ \"can_vote\")"
 
-#: models.py:68
+#: .\models.py:63
 msgid "With auth"
 msgstr "С авторизацией"
 
-#: models.py:70
+#: .\models.py:65
 msgid "Without auth"
 msgstr "Без авторизации"
 
-#: models.py:77
+#: .\models.py:72
 msgid "Queues"
 msgstr "Очереди"
 
-#: models.py:81
+#: .\models.py:76
 msgid "Its userbox?"
 msgstr "Это пользовательский ввод?"
 
-#: models.py:81
+#: .\models.py:76
 msgid "Set it, if you want user to type its own answer. (show as textbox)"
 msgstr ""
 "Выберете это, если вы хотите что бы пользователь сам напечатал свой ответ "
 "(вывод textbox)"
 
-#: models.py:82
+#: .\models.py:77
 msgid "Value"
 msgstr "Значение"
 
-#: models.py:82
+#: .\models.py:77
 msgid "Its a title of item"
 msgstr "Заголовок item"
 
-#: models.py:83
+#: .\models.py:78
 msgid "Position"
 msgstr "Позиция"
 
-#: models.py:83
+#: .\models.py:78
 msgid "Its for positioning only"
 msgstr "Только для позиционирования"
 
-#: models.py:93
+#: .\models.py:88
 msgid "User's IP"
 msgstr "IP пользователя"
 
-#: models.py:94 templates/polls.html:136
+#: .\models.py:89 .\templates\polls.html.py:25
 msgid "User"
 msgstr "Пользователь"
 
-#: models.py:96
+#: .\models.py:91
 msgid "Voited items"
 msgstr "Голосовавшие items"
 
-#: models.py:104 templates/polls.html:145
+#: .\models.py:99 .\templates\polls.html.py:34
 msgid "Vote"
 msgstr "Голос"
 
-#: templates/polls.html:59
+#: .\templates\polls.html.py:8
 msgid "Total Voters"
 msgstr "Всего"
 
-#: templates/polls.html:109
+#: .\templates\polls.html.py:9
 msgid "Please, choose anything to vote"
 msgstr "Пожалуйста выберете что-нибудь чтобы проголосовать"
 
-#: templates/polls.html:128
+#: .\templates\polls.html.py:10
+msgid "Only authenticated users can vote"
+msgstr "Только авторизированные пользователи могут голосовать"
+
+#: .\templates\polls.html.py:17
 msgid ""
 "WARNING: JavaScript is disabled in your browser. Please, turn it on to vote."
 msgstr ""
 "JavaScript отключен в вашем браузере. Вы должны включить его, чтобы "
 "проголосовать."
 
-#: templates/polls.html:141
+#: .\templates\polls.html.py:30
 msgid "You already voted"
 msgstr "Вы уже проголосовали"
 
-#: templates/polls.html:142
+#: .\templates\polls.html.py:31
 msgid "Show results"
 msgstr "Показать результаты"
 
-#: templates/polls.html:151
+#: .\templates\polls.html.py:40
 msgid ""
 "WARNING: Cookies are disabled in your browser. Please, turn it on to vote."
 msgstr ""
 "Cookies отключены в вашем браузере. Вы должны включить их, чтобы "
 "проголосовать."
+
 from django.db.models.manager import Manager
 from django.core.exceptions import ValidationError
 
-class PollType(models.Model):
-    title = models.CharField(max_length=150, verbose_name=_('Type title'), help_text=_('It will be used as header of the poll'))
-    index = models.SmallIntegerField(unique=True, verbose_name=_('Index'), help_text=_('Must be unique'))
-    
-    def __unicode__(self):
-        return '%s (%d)' % (self.title, self.index)
-    
-    class Meta:
-        ordering = ['-index']
-        verbose_name = _('PollType')
-        verbose_name_plural = _('PollTypes')
-        
+POLLTYPE_CHOICES = (
+        ('0', 'Single'),
+        ('1', 'Multiple'),
+    )
+
 class PublishManager(Manager):
     def get_query_set(self):
         return super(PublishManager, self).get_query_set().filter(publish=True)
 class Poll(models.Model):
     title = models.CharField(max_length=250, verbose_name=_('Title'), help_text=_('The parameter is used as question to user'))
     queue = models.ForeignKey('Queue', blank=True, null=True, verbose_name=_('Queue'), help_text=_('Do you want to use the poll as a stand alone poll or insert it into the queue?'))
-    polltype = models.ForeignKey(PollType, verbose_name=_('Poll type'), help_text=_('Choose the poll type'))
+    polltype =  models.CharField(max_length=1, choices=POLLTYPE_CHOICES, verbose_name=_('Poll type'), help_text=_('Choose the poll type'))
     startdate = models.DateField(verbose_name=_('Start date'), help_text=_('Must be unique'))
     publish = models.BooleanField(default=True, verbose_name=_('Publish'))
     votes = models.ManyToManyField('Vote', related_name='%(app_label)s_%(class)s_related', blank=True, verbose_name=_('Votes'), help_text=_('Choose variants of answers'))
     def __unicode__(self):
         return self.title
     
+    def print_polltype(self):
+        return POLLTYPE_CHOICES[int(self.polltype)][1]
+    
     class Meta:
         ordering = ['-startdate']
         verbose_name = _('Poll')
         verbose_name_plural = _('Polls')
-        permissions = (("can_vote", _("User can vote")),)
         
 class Queue(models.Model):
     title = models.CharField(unique=True, max_length=250, verbose_name=_('Queue name'), help_text=_('It must be unique'))

poll/templates/_polls_script.js

 	var vote_url = '{% url poll_ajax_vote poll.pk %}';
 	var result_url = '{% url poll_ajax_result poll.pk %}';
 	var poll_pk = '{{ poll.pk }}';
-	var poll_type = {% if poll.polltype.index == 0 %}'single'{% else %}'multiple'{% endif %};
+	var poll_type = '{{ poll_type }}';
+	var can_vote = ('{{ can_vote }}' === 'True')? true : false;
 	
 	var path_to_items = '.dps_poll_content_' + poll_pk + ' .dps_poll_body input[name="poll_' + poll_pk + '"]';
 	var body = $('.dps_poll_content_' + poll_pk + ' .dps_poll_body');
 	function showResults(data) {
 		var show_points = false;
 		var all_points = 0, total = 0, biggest = 0;
+
+		if(poll_type == 'Multiple') {
+			show_points = true;
+		}
 		
 		body.hide('slow', complete=function() {
 			body.empty();
 				total_points_txt = '<sup>(' + all_points + ')</sup>'; 
 			}
 			
-			body.append('<div class="dps_poll_voters_count">' + '{% trans "Total Voters" %}' + ': <span class="dps_poll_total">' + total + '</span> ' + total_points_txt + '</div>');
+			body.append('<div class="dps_poll_voters_count">' + trans_total_voters + ': <span class="dps_poll_total">' + total + '</span> ' + total_points_txt + '</div>');
 		}).show('slow');
 	}
 	
 	}
 	
 	$(path_to_items).bind('focusin click', function() {
-		if(poll_type == 'single') {
+		if(poll_type == 'Single') {
 			var selected = this;
 			
 			$(path_to_items).map(function() {
 		var result = RecognizeAndPrepare();
 		
 		if(result == '{}') {
-			alert('{% trans "Please, choose anything to vote" %}');
+			alert(trans_choose_anything_to_vote);
 		} else {
+			if(!can_vote) {
+				alert(trans_only_authenticated_users_can_vote);
+				return;
+			}
 			body.hide('slow', complete=function() {
 				$.get(vote_url, {'chosen_items': result}, function() {
 					doResults();
 	$(".dps_showresults_" + poll_pk).click(function() {
 		doResults();
 	});
-});
+});

poll/templates/polls.html

 {% load i18n %}
 {% load polls_tags %}
 
-{% if poll %}
 <style type="text/css">
 	{% include "_polls_style.css" %}
 </style>
 <script type="text/javascript">
+	trans_total_voters = '{% trans "Total Voters" %}';
+	trans_choose_anything_to_vote = '{% trans "Please, choose anything to vote" %}';
+	trans_only_authenticated_users_can_vote = '{% trans "Only authenticated users can vote" %}';
 	{% include "_polls_script.js" %}
 </script>
 
 		}
 	</script>
 </div>
-{% endif %}

poll/templatetags/polls_tags.py

 from django import template
-from poll.models import Poll, Item, Queue, Vote
+from poll.models import Poll, Item, Queue
 from settings import STATIC_URL
 from django.utils.safestring import SafeUnicode
 from django.utils.datetime_safe import datetime
-from poll.ajax import authpassQueue
+from poll.ajax import authpass
 
 register = template.Library()
-
 @register.inclusion_tag('polls.html', takes_context=True)
 def poll(context, poll):
-    return {'poll': poll, 'items': Item.objects.filter(poll=poll), 'user': context['user'], 'request': context['request'], 'STATIC_URL': STATIC_URL}
+    can_vote = True
+    if poll.queue:
+        can_vote = authpass(context['user'], poll.queue)
+    return {'poll': poll, 'poll_type': poll.print_polltype(), 'items': Item.objects.filter(poll=poll), 'user': context['user'], 'can_vote': can_vote, 'request': context['request'], 'STATIC_URL': STATIC_URL}
 
 @register.inclusion_tag('polls.html', takes_context=True)
 def poll_queue(context, queue):
-    if isinstance(queue, SafeUnicode):
-        tmp_queue = Queue.objects.get(title=queue)
+    try:
+        if isinstance(queue, SafeUnicode):
+            tmp_queue = Queue.objects.get(title=queue)
+        else:
+            tmp_queue = Queue.objects.get(queue)
+    except:
+        raise Exception('Queue not found')
+    
+    tmp_polls = Poll.publish_manager.filter(queue=tmp_queue, startdate__lte=datetime.now())
+    
+    if len(tmp_polls) > 0:
+        cur_poll = tmp_polls[0]
     else:
-        tmp_queue = Queue.objects.get(queue)
+        cur_poll = None
     
-    if authpassQueue(context['user'], tmp_queue):
-        tmp_polls = Poll.publish_manager.filter(queue=tmp_queue, startdate__lte=datetime.now())
-        
-        if len(tmp_polls) > 0:
-            cur_poll = tmp_polls[0]
-        else:
-            cur_poll = None
-        
-        return poll(context, cur_poll)
+    return poll(context, cur_poll)
 
 class RenderItemsClass(template.Node):
     def __init__(self, poll, items):
                 input_type = 'textbox'
                 pattern = pattern1
             else:
-                if poll.polltype.index == 0:
+                poll_type = poll.print_polltype()
+                
+                if poll_type == 'Single':
                     input_type = 'radio'
-                elif poll.polltype.index == 1:
+                elif poll_type == 'Multiple':
                     input_type = 'checkbox'
                 pattern = pattern2
                     
 from distutils.core import setup
 
 setup(name='django-poll-system',
-      version='0.1.1',
+      version='0.2.0',
       description='The application to organize polling (or voting) on your site.',
       author='RafRaf',
       maintainer='RafRaf',