RafRaf avatar RafRaf committed 75f9161

The code is edited according to PEP8

Comments (0)

Files changed (8)

 from poll.models import Poll, Item, Queue, Vote, Choice
 from django.utils.translation import gettext as _
 
+
 class PollItemInline(admin.TabularInline):
     model = Item
     extra = 5
     max_num = 10
 
+
 class PollAdmin(admin.ModelAdmin):
-    list_display = ('title', 'queue', 'startdate', 'polltype', 'vote_count', 'publish')
-    
+    list_display = ('title', 'queue', 'startdate', 'polltype', 'vote_count',
+                    'publish')
     inlines = [
         PollItemInline,
     ]
 
     fieldsets = (
                  (None, {'fields': ('title',)}),
-                 (_('Options'), {'fields': ('publish', 'polltype', 'queue', 'startdate',)}),
+                 (_('Options'), {'fields': ('publish', 'polltype', 'queue',
+                                            'startdate',)}),
                  )
 
+
 class VoteChoiceItemInline(admin.TabularInline):
     model = Choice
     extra = 5
     max_num = 10
     readonly_fields = ('item', 'uservalue')
 
+
 class VoteAdmin(admin.ModelAdmin):
     list_display = ('poll', 'ip', 'user', 'datetime')
     list_filter = ('poll', 'datetime')
-    
     inlines = [
         VoteChoiceItemInline,
     ]
 from django.utils import simplejson
 from utils import set_cookie
 
+
 def authpass(user, queue):
     if queue != None:
         if queue.auth:
                 return False
     return True
 
+
 #TODO: Need to optimize
 @transaction.commit_on_success
 def poll_ajax_vote(request, poll_pk):
     if request.is_ajax():
         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)
-            
+                    return HttpResponse('Non-authenticated users can\'t vote',
+                                        status=400)
+
             chosen_items = simplejson.loads(request.GET['chosen_items'])
         except:
             return HttpResponse('Wrong parameters', status=400)
-        
+
         if request.user.is_authenticated():
             user = request.user
         else:
             user = None
-        
+
         vote = Vote.objects.create(poll=poll,
                                    ip=request.META['REMOTE_ADDR'],
                                    user=user)
         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)
+                    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)
-        
+
         return response
+
     return HttpResponse(status=400)
 
+
 def poll_ajax_result(request, poll_pk):
     if request.is_ajax():
         try:
             poll = Poll.objects.get(pk=poll_pk)
         except:
             return HttpResponse('Wrong parameters', status=400)
-        
+
         #Send data for results
         data = {}
-        
+
         for item in Item.objects.filter(poll=poll):
             subdata = {
                        'index': item.index,
                        'title': item.value,
                        'count': Choice.objects.filter(item=item).count(),
                        }
-            
+
             data[item.pk] = subdata
-            
+
         data['total'] = Vote.objects.filter(poll=poll).count()
-        
+
         return HttpResponse(simplejson.dumps(data))
-    return HttpResponse(status=400)
+    return HttpResponse(status=400)
Add a comment to this file

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-02-03 13:41+0400\n"
+"POT-Creation-Date: 2012-02-04 21:00+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"
-"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"
+"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:21
 msgid "Options"
 msgstr "Опции"
 
-#: .\models.py:17
+#: models.py:21
 msgid "Title"
 msgstr "Заголовок"
 
-#: .\models.py:17
+#: models.py:22
 msgid "The parameter is used as question to user"
 msgstr "Параметр используется как заголовок вопроса к пользователю"
 
-#: .\models.py:18 .\models.py:71
+#: models.py:26 models.py:95
 msgid "Queue"
 msgstr "Очередь"
 
-#: .\models.py:18
+#: models.py:27
 msgid ""
 "Do you want to use the poll as a stand alone poll or insert it into the "
 "queue?"
 "Вы хотите использовать опрос как отдельностоящий опрос или вставить его в "
 "очередь?"
 
-#: .\models.py:19
+#: models.py:30
 msgid "Poll type"
 msgstr "Тип опроса"
 
-#: .\models.py:19
+#: models.py:31
 msgid "Choose the poll type"
 msgstr "Выберете тип опроса"
 
-#: .\models.py:20
+#: models.py:32
 msgid "Start date"
 msgstr "Дата старта"
 
-#: .\models.py:20
+#: models.py:33
 msgid "Must be unique"
 msgstr "Должен быть уникальным"
 
-#: .\models.py:21
+#: models.py:34
 msgid "Publish"
 msgstr "Публиковать"
 
-#: .\models.py:22 .\models.py:100
+#: models.py:38 models.py:136
 msgid "Votes"
 msgstr "Голоса"
 
-#: .\models.py:22
+#: models.py:39
 msgid "Choose variants of answers"
 msgstr "Выберете варианты ответов"
 
-#: .\models.py:29
+#: models.py:46
 msgid "\"Start dates\" of polls in the same queue must be different"
 msgstr ""
 "Параметры \"Start dates\" у разных опросов в одной очереди должны быть "
 "отличны"
 
-#: .\models.py:54 .\models.py:87 .\templates\polls.html.py:22
+#: models.py:73 models.py:118 templates/polls.html:22
 msgid "Poll"
 msgstr "Опрос"
 
-#: .\models.py:55
+#: models.py:74
 msgid "Polls"
 msgstr "Опросы"
 
-#: .\models.py:58
+#: models.py:80
 msgid "Queue name"
 msgstr "Название очереди"
 
-#: .\models.py:58
+#: models.py:81
 msgid "It must be unique"
 msgstr "Должен быть уникальным"
 
-#: .\models.py:59
+#: models.py:82
 msgid "Need auth?"
 msgstr "Нужна аутентификация?"
 
-#: .\models.py:59
+#: models.py:83
 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:63
+#: models.py:87
 msgid "With auth"
 msgstr "С авторизацией"
 
-#: .\models.py:65
+#: models.py:89
 msgid "Without auth"
 msgstr "Без авторизации"
 
-#: .\models.py:72
+#: models.py:96
 msgid "Queues"
 msgstr "Очереди"
 
-#: .\models.py:76
+#: models.py:101
 msgid "Its userbox?"
 msgstr "Это пользовательский ввод?"
 
-#: .\models.py:76
+#: models.py:102
 msgid "Set it, if you want user to type its own answer. (show as textbox)"
 msgstr ""
 "Выберете это, если вы хотите что бы пользователь сам напечатал свой ответ "
 "(вывод textbox)"
 
-#: .\models.py:77
+#: models.py:104
 msgid "Value"
 msgstr "Значение"
 
-#: .\models.py:77
+#: models.py:105
 msgid "Its a title of item"
 msgstr "Заголовок item"
 
-#: .\models.py:78
+#: models.py:107
 msgid "Position"
 msgstr "Позиция"
 
-#: .\models.py:78
+#: models.py:108
 msgid "Its for positioning only"
 msgstr "Только для позиционирования"
 
-#: .\models.py:88
+#: models.py:119
 msgid "User's IP"
 msgstr "IP пользователя"
 
-#: .\models.py:89 .\templates\polls.html.py:25
+#: models.py:123 templates/polls.html:25
 msgid "User"
 msgstr "Пользователь"
 
-#: .\models.py:91
+#: models.py:127
 msgid "Voited items"
 msgstr "Голосовавшие items"
 
-#: .\models.py:99 .\templates\polls.html.py:34
+#: models.py:135 templates/polls.html:34
 msgid "Vote"
 msgstr "Голос"
 
-#: .\templates\polls.html.py:8
+#: templates/polls.html:8
 msgid "Total Voters"
 msgstr "Всего"
 
-#: .\templates\polls.html.py:9
+#: templates/polls.html:9
 msgid "Please, choose anything to vote"
 msgstr "Пожалуйста выберете что-нибудь чтобы проголосовать"
 
-#: .\templates\polls.html.py:10
+#: templates/polls.html:10
 msgid "Only authenticated users can vote"
 msgstr "Только авторизированные пользователи могут голосовать"
 
-#: .\templates\polls.html.py:17
+#: templates/polls.html:17
 msgid ""
 "WARNING: JavaScript is disabled in your browser. Please, turn it on to vote."
 msgstr ""
 "JavaScript отключен в вашем браузере. Вы должны включить его, чтобы "
 "проголосовать."
 
-#: .\templates\polls.html.py:30
+#: templates/polls.html:30
 msgid "You already voted"
 msgstr "Вы уже проголосовали"
 
-#: .\templates\polls.html.py:31
+#: templates/polls.html:31
 msgid "Show results"
 msgstr "Показать результаты"
 
-#: .\templates\polls.html.py:40
+#: templates/polls.html: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
 
+
 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.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'))
+    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.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'))
-    
+    votes = models.ManyToManyField('Vote',
+                                   related_name='%(app_label)s_%(class)s_related',
+                                   blank=True,
+                                   verbose_name=_('Votes'),
+                                   help_text=_('Choose variants of answers'))
+
     objects = models.Manager()
     publish_manager = PublishManager()
-    
+
     def clean(self):
         if self.queue is not None:
             err_msg = _('"Start dates" of polls in the same queue must be different')
-            objs = Poll.objects.filter(queue=self.queue, startdate=self.startdate)
+            objs = Poll.objects.filter(queue=self.queue,
+                                       startdate=self.startdate)
             count = objs.count()
-            
+
             if count > 1:
                 raise ValidationError(err_msg)
             elif count == 1:
                 if objs[0] != self:
                     raise ValidationError(err_msg)
-    
+
     def get_vote_count(self):
         return Vote.objects.filter(poll=self).count()
+
     vote_count = property(fget=get_vote_count)
-    
+
     def get_cookie_name(self):
-        return str('poll_%s' % (self.pk)) 
-    
+        return str('poll_%s' % (self.pk))
+
     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')
-        
+
+
 class Queue(models.Model):
-    title = models.CharField(unique=True, max_length=250, verbose_name=_('Queue name'), help_text=_('It must be unique'))
-    auth = models.BooleanField(verbose_name=_('Need auth?'), help_text=_('Do the poll queue is for authenticated users only or not? (If yes, users must have "can_vote" permission to vote)'))
-    
+    title = models.CharField(unique=True,
+                             max_length=250,
+                             verbose_name=_('Queue name'),
+                             help_text=_('It must be unique'))
+    auth = models.BooleanField(verbose_name=_('Need auth?'),
+                               help_text=_('Do the poll queue is for authenticated users only or not? (If yes, users must have "can_vote" permission to vote)'))
+
     def __unicode__(self):
         if self.auth:
             auth = _('With auth')
         else:
             auth = _('Without auth')
-        
+
         return '%s (%s)' % (self.title, auth)
-    
+
     class Meta:
         ordering = ['-title']
         verbose_name = _('Queue')
         verbose_name_plural = _('Queues')
 
+
 class Item(models.Model):
     poll = models.ForeignKey(Poll)
-    userbox = models.BooleanField(verbose_name=_('Its userbox?'), help_text=_('Set it, if you want user to type its own answer. (show as textbox)'))
-    value = models.CharField(max_length=250, verbose_name=_('Value'), help_text=_('Its a title of item'))
-    index = models.SmallIntegerField(default='0', verbose_name=_('Position'), help_text=_('Its for positioning only'))
-    
+    userbox = models.BooleanField(verbose_name=_('Its userbox?'),
+                                  help_text=_('Set it, if you want user to type its own answer. (show as textbox)'))
+    value = models.CharField(max_length=250,
+                             verbose_name=_('Value'),
+                             help_text=_('Its a title of item'))
+    index = models.SmallIntegerField(default='0',
+                                     verbose_name=_('Position'),
+                                     help_text=_('Its for positioning only'))
+
     def __unicode__(self):
         return '%s (%d)' % (self.value, self.index)
-    
+
     class Meta:
         ordering = ['index']
 
+
 class Vote(models.Model):
     poll = models.ForeignKey(Poll, verbose_name=_('Poll'))
     ip = models.IPAddressField(verbose_name=_('User\'s IP'))
-    user = models.ForeignKey(User, blank=True, null=True, verbose_name=_('User'))
+    user = models.ForeignKey(User,
+                             blank=True,
+                             null=True,
+                             verbose_name=_('User'))
     datetime = models.DateTimeField(auto_now_add=True)
-    choices = models.ManyToManyField(Item, through='Choice', verbose_name=_('Voited items'))
-    
+    choices = models.ManyToManyField(Item,
+                                     through='Choice',
+                                     verbose_name=_('Voited items'))
+
     def __unicode__(self):
         if isinstance(self.user, User):
             return self.user.username
         return self.ip
-    
+
     class Meta:
         verbose_name = _('Vote')
         verbose_name_plural = _('Votes')
-        
+
+
 class Choice(models.Model):
     vote = models.ForeignKey(Vote)
     item = models.ForeignKey(Item)
-    uservalue = models.CharField(max_length=250, blank=True, null=True)
+    uservalue = models.CharField(max_length=250, blank=True, null=True)

poll/templatetags/polls_tags.py

 from django.utils.datetime_safe import datetime
 from poll.ajax import authpass
 
+
 register = template.Library()
+
+
 @register.inclusion_tag('polls.html', takes_context=True)
 def poll(context, poll):
     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}
+    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):
             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())
-    
+
+    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)
 
+
 class RenderItemsClass(template.Node):
     def __init__(self, poll, items):
-        self.poll=template.Variable(poll)
-        self.items=template.Variable(items)
-        
+        self.poll = template.Variable(poll)
+        self.items = template.Variable(items)
+
     def render(self, context):
         poll = self.poll.resolve(context)
         items = self.items.resolve(context)
         #'name' = item.pk
-        pattern1 = '{3}<br /><input name="poll_{0}" type="{1}" id="{2}" value="" /><br />'
+        pattern1 = '{3}<br /><input name="poll_{0}" ' \
+                   'type="{1}" id="{2}" value="" /><br />'
         pattern2 = '<input name="poll_{0}" type="{1}" id="{2}" /> {3}<br />'
         result = ''
-        
+
         #Choose an input type
         for item in items:
             if item.userbox:
                 pattern = pattern1
             else:
                 poll_type = poll.print_polltype()
-                
+
                 if poll_type == 'Single':
                     input_type = 'radio'
                 elif poll_type == 'Multiple':
                     input_type = 'checkbox'
                 pattern = pattern2
-                    
+
             result += pattern.format(poll.pk, input_type, item.pk, item.value)
-            
+
         return result
 
+
 @register.tag
 def render_items(parser, token):
     tag, poll, items = token.split_contents()
-    return RenderItemsClass(poll, items)
+    return RenderItemsClass(poll, items)
 from poll.ajax import poll_ajax_vote, poll_ajax_result
 
 urlpatterns = patterns('',
-    url(r'^vote/(?P<poll_pk>\d)$', poll_ajax_vote, name='poll_ajax_vote'),
-    url(r'^result/(?P<poll_pk>\d)$', poll_ajax_result, name='poll_ajax_result'),
-)
+    url(r'^vote/(?P<poll_pk>\d)$',
+        poll_ajax_vote,
+        name='poll_ajax_vote'),
+    url(r'^result/(?P<poll_pk>\d)$',
+        poll_ajax_result,
+        name='poll_ajax_result'),
+)
 import datetime
 
-def set_cookie(response, key, value, days_expire = 90):
+
+def set_cookie(response, key, value, days_expire=90):
     if days_expire is None:
-        max_age = 365 * 24 * 60 * 60    #one year
+        #one year
+        max_age = 365 * 24 * 60 * 60
     else:
-        max_age = days_expire * 24 * 60 * 60 
-    expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT")
-    response.set_cookie(key, value, max_age=max_age, expires=expires)
+        max_age = days_expire * 24 * 60 * 60
+    expires = datetime.datetime.strftime(datetime.datetime.utcnow() +
+                                         datetime.timedelta(seconds=max_age),
+                                         "%a, %d-%b-%Y %H:%M:%S GMT")
+    response.set_cookie(key, value, max_age=max_age, expires=expires)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.