Commits

Bertrand Bordage committed 101f11e Draft

Code cleanup.

Comments (0)

Files changed (9)

cmsplugin_poll/admin.py

 from django.contrib import admin
 from django.utils.translation import ugettext_lazy as _
 
+
 def make_closed(modeladmin, request, queryset):
-    queryset.update(close_date=datetime.datetime.now())
+    queryset['close_date'] = datetime.datetime.now()
 make_closed.short_description = _("Close selected polls")
 
+
 class ChoiceInline(admin.TabularInline):
     model = Choice
     extra = 5
 
+
 class PollAdmin(admin.ModelAdmin):
     fieldsets = [
         (None,                     {"fields": ["question"]}),
         (_("Date information"),    {"fields": ["pub_date"]})
-        ]
+    ]
     inlines = [ChoiceInline]
     actions = [make_closed]
 

cmsplugin_poll/cms_plugins.py

 from cms.plugin_base import CMSPluginBase
 from cms.plugin_pool import plugin_pool
-from cmsplugin_poll.models import *
+from cmsplugin_poll.models import PollPlugin
 from django.utils.translation import ugettext as _
 
+
 class CMSPollPlugin(CMSPluginBase):
     model = PollPlugin
     name = _("Simple poll")
 
     def render(self, context, instance, placeholder):
         context.update({
-                "poll" : instance.poll,
+                "poll": instance.poll,
                 })
         return context
 

cmsplugin_poll/models.py

 from django.utils.translation import ugettext_lazy as _
 from cms.models import CMSPlugin
 
+
 class Poll(models.Model):
     question = models.CharField(_('question'), max_length=300)
     pub_date = models.DateTimeField(_('date published'))
     class Meta:
         verbose_name = _('Poll')
         verbose_name_plural = _('Polls')
+        ordering = ('-pub_date',)
 
     def __unicode__(self):
         return unicode(self.question)
 
     @property
     def votes(self):
-        res = 0
-        for c in self.choice_set.all():
-            res += c.votes
-        return res
+        return self.choice_set.aggregate(models.Sum('votes'))['votes__sum']
 
     def getrate(self, choice):
         total = self.votes
         if not total:
             return total
-        return choice.votes / float(total) * 100.0
+        return 100.0 * choice.votes / float(total)
+
 
 class Choice(models.Model):
     poll = models.ForeignKey(Poll, verbose_name=_('poll'))
     def __unicode__(self):
         return '%s (%s)' % (self.choice, self.poll)
 
+
 class PollPlugin(CMSPlugin):
     poll = models.ForeignKey(Poll, verbose_name=_("Poll to display"))
 
 
     def __str__(self):
         return self.poll.question
-

cmsplugin_poll/templates/cmsplugin_poll/detail.html

 {% load i18n %}
+
 <h3>{% trans "Poll" %}</h3>
-<p><a href="{% url cmsplugin_poll.views.results poll.id %}">{{ poll.question }}</a></p>
+<p>
+  <a href="{% url cmsplugin_poll.views.results poll.id %}">
+    {{ poll.question }}
+  </a>
+</p>
+
 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
+
 <form action="{% url cmsplugin_poll.views.vote poll.id %}" method="post">
   {% csrf_token %}
-  {% for choice in poll.choice_set.all %}
-  <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
-  <label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
+  {% for choice in poll.choice_set.iterator %}
+    <input type="radio" name="choice"
+           id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
+    <label for="choice{{ forloop.counter }}">
+      {{ choice.choice }}
+    </label><br />
   {% endfor %}
   <input type="submit" value='{% trans "Vote" %}' />
 </form>

cmsplugin_poll/templates/cmsplugin_poll/latest_polls.html

 {% load i18n %}
+
 <h3>{% trans "Previous polls" %}</h3>
 {% if polls %}
-<ul>
-  {% for poll in polls %}
-  <li><a href="{% url cmsplugin_poll.views.results poll.id %}">{{ poll.question }}</a></li>
-  {% endfor %}
-</ul>
+  <ul>
+    {% for poll in polls %}
+      <li>
+        <a href="{% url cmsplugin_poll.views.results poll.id %}">
+          {{ poll.question }}
+        </a>
+      </li>
+    {% endfor %}
+  </ul>
 {% else %}
-<p>{% trans "No polls are available." %}</p>
+  <p>{% trans "No polls are available." %}</p>
 {% endif %}

cmsplugin_poll/templates/cmsplugin_poll/results.html

 {% load i18n poll_tags %}
+
 <h2>{% trans "Poll results" %}</h2>
 {% if messages %}
-<div class="messages">
-  {% for message in messages %}
-  <span{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}.</span>
-  {% endfor %}
-</div>
+  <div class="messages">
+    {% for message in messages %}
+      <span{% if message.tags %} class="{{ message.tags }}"{% endif %}>
+        {{ message }}.
+      </span>
+    {% endfor %}
+  </div>
 {% endif %}
+
 <h3>{{ poll.question }}</h3>
 <ul>
-{% for choice in poll.choice_set.all %}
-    <li>{{ choice.choice }} ({{ choice.votes }} vote{{ choice.votes|pluralize }}, {% get_choice_rate poll choice %})</li>
+  {% for choice in poll.choice_set.iterator %}
+    <li>
+      {{ choice.choice }}
+      ({{ choice.votes }} vote{{ choice.votes|pluralize }},
+      {% get_choice_rate poll choice %})
+    </li>
     <div name="choice" id="{{ choice.votes }}"></div>
-{% endfor %}
+  {% endfor %}
 </ul>

cmsplugin_poll/templatetags/poll_tags.py

 
 @register.simple_tag
 def get_latest_polls(count=5):
-    polls = Poll.objects.all().order_by("-pub_date")[:5]
+    "FIXME: I'm useless!"
+    polls = Poll.objects.all()[:5]
     return render_to_string("cmsplugin_poll/latest_polls.html", {
             "polls" : polls
             })

cmsplugin_poll/urls.py

-from django.conf.urls.defaults import *
+from django.conf.urls.defaults import patterns
 
 urlpatterns = patterns('cmsplugin_poll.views',
     (r'^$', 'index'),

cmsplugin_poll/views.py

 from django.shortcuts import render_to_response, get_object_or_404
-from django.http import HttpResponseRedirect, HttpResponse
+from django.http import HttpResponseRedirect
 from django.core.urlresolvers import reverse
 from django.template import RequestContext
 from django.contrib import messages
 from django.utils.translation import ugettext_lazy as _
-from models import *
+from models import Poll, Choice
+
 
 def index(request):
-    polls = Poll.objects.all().order_by("-pub_date")
+    polls = Poll.objects.iterator()
     return render_to_response("cmsplugin_poll/latest_polls.html", {
-            "polls" : polls
+            "polls": polls
             })
 
+
 def detail(request, poll_id):
     p = get_object_or_404(Poll, pk=poll_id)
-    return render_to_response("cmsplugin_poll/detail.html", {"poll" : p},
+    return render_to_response("cmsplugin_poll/detail.html", {"poll": p},
                               context_instance=RequestContext(request))
 
+
 def vote(request, poll_id):
     p = get_object_or_404(Poll, pk=poll_id)
     if p.close_date is not None:
             selected_choice.save()
             messages.info(request, _("Thank you for your vote"))
             request.session["poll_%d" % p.id] = True
-    return HttpResponseRedirect(reverse('cmsplugin_poll.views.results', 
+    return HttpResponseRedirect(reverse('cmsplugin_poll.views.results',
                                         args=(p.id,)))
 
+
 def results(request, poll_id):
     p = get_object_or_404(Poll, pk=poll_id)
     return render_to_response('cmsplugin_poll/results.html', {'poll': p},
                               context_instance=RequestContext(request))
-
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.