Advertisement
Guest User

Untitled

a guest
Jan 3rd, 2014
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.40 KB | None | 0 0
  1. **********************************************
  2. views.py
  3. **********************************************
  4.  
  5. from django.shortcuts import render, HttpResponseRedirect, \
  6.     redirect, get_object_or_404
  7.  
  8. from polls.models import Poll
  9.  
  10. def index(request):
  11.     polls = Poll.objects.all()
  12.     # if request.method == 'POST':
  13.     #     if request.POST['answer-1']:
  14.     #         answer = Answer(
  15.     #                 )
  16.     #         answer.save()
  17.     #         return HttpResponseRedirect('results')
  18.     # else:
  19.     context = {'polls': polls}
  20.     return render(request, 'index.html', context)
  21.  
  22. def detail(request, question_id):
  23.     return HttpResponse("You're looking at question %s." % question_id)
  24.  
  25. def vote(request, poll_id):
  26.     p = get_object_or_404(Poll, pk=poll_id)
  27.     if request.POST['choice'] == 'yes':
  28.         p.yes += 1
  29.     if request.POST['choice'] == 'no':
  30.         p.no += 1
  31.     p.save()
  32.     return HttpResponseRedirect('/')
  33.  
  34. def ajax_vote(request, poll_id):
  35.     p = get_object_or_404(Poll, pk=poll_id)
  36.     if request.POST['choice'] == 'yes':
  37.         p.yes += 1
  38.     if request.POST['choice'] == 'no':
  39.         p.no += 1
  40.     p.save()
  41.     print 'AJAX'
  42.     # import ipdb;
  43.     # ipdb.set_trace();
  44.     return HttpResponseRedirect(p.get_absolute_url())
  45.  
  46.  
  47. **********************************************
  48. index.html
  49. **********************************************
  50.  
  51. {% extends 'base.html' %}
  52.  
  53. {% block content %}
  54.  
  55. <div class="container">
  56.  
  57.  
  58.         <div class="clear"></div> -->
  59.        
  60.         {% for poll in polls %}
  61.         <div class="clear"></div>
  62.         <div class="container poll-box">
  63.             <form action="{% url 'polls:vote' poll.id %}" method="post">
  64.             {% csrf_token %}
  65.  
  66.                 <div class="responsiveWrapper poll-item">{{ poll.text|safe }}</div>
  67.                
  68.                 <div class="clear">&nbsp;</div>
  69.  
  70.                 <div class="yes">
  71.                     <input type="radio" name="choice" id="choice-yes-{{ poll.id }}" value="yes" class="yes">
  72.                     <label for="choice-yes-{{ poll.id }}">This is terrorism</label>
  73.                 </div>
  74.  
  75.                 <div class="no">
  76.                     <input type="radio" name="choice" id="choice-no-{{ poll.id }}" value="no" class="no">
  77.                     <label for="choice-no-{{ poll.id }}">This is not terrorism</label><br />
  78.                 </div>
  79.  
  80.                 <div class="clear"></div>
  81.                 <p id="vote-button"><input type="submit" value="Vote&raquo;" class="btn btn-primary btn-large" id="vote" /></p>
  82.             </form>
  83.         </div>
  84. {% endfor %}
  85.  
  86. </div>
  87. </div>
  88.  
  89. <script type="text/javascript">
  90.     $(document).ready(function() {
  91.  
  92.     var create_vote = function() {
  93.     var value = $("form input[name='choice']:checked").val();
  94.  
  95.     if (value != "")
  96.     {
  97.         var data = { choice:value };
  98.         var args = { type:"POST", url:"/ajax_vote/2/", data:data, complete:create_vote_complete };
  99.         $.ajax(args);
  100.     }
  101.     else
  102.     {
  103.         // We should display a helpful error message
  104.         "Something wrong"
  105.     }
  106.     return false;
  107.     };
  108.  
  109.     var create_vote_complete = function(res, status) {
  110.         if (status == "success") {
  111.             window.location.href = "/";
  112.         }
  113.         else
  114.         {
  115.             display_message(res.responseText, $(".message"));
  116.         }
  117.     }
  118.  
  119.     var display_message = function(msg, elem) {
  120.         var msg_div = $('<div><p>'+msg+'</p></div>');
  121.         elem.append(msg_div).fadeIn('slow').animate({opacity: 1.0}, 7000).fadeOut('slow',function() { msg_div.remove(); });
  122.     };
  123.  
  124.     function getCookie(name) {
  125.         var cookieValue = null;
  126.         if (document.cookie && document.cookie != '') {
  127.             var cookies = document.cookie.split(';');
  128.             for (var i = 0; i < cookies.length; i++) {
  129.                 var cookie = jQuery.trim(cookies[i]);
  130.                 // Does this cookie string begin with the name we want?
  131.                 if (cookie.substring(0, name.length + 1) == (name + '=')) {
  132.                     cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
  133.                     break;
  134.                 }
  135.             }
  136.         }
  137.         return cookieValue;
  138.     }
  139.     var csrftoken = getCookie('csrftoken');
  140.  
  141.     function csrfSafeMethod(method) {
  142.         // these HTTP methods do not require CSRF protection
  143.         return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  144.     }
  145.     $.ajaxSetup({
  146.         crossDomain: false, // obviates need for sameOrigin test
  147.         beforeSend: function(xhr, settings) {
  148.             if (!csrfSafeMethod(settings.type)) {
  149.                 xhr.setRequestHeader("X-CSRFToken", csrftoken);
  150.             }
  151.         }
  152.     });
  153.     $("#vote").click(create_vote);
  154.  
  155.     });
  156. </script>
  157.  
  158. {% endblock %}
  159.  
  160.  
  161. **********************************************
  162. models.py
  163. **********************************************
  164.  
  165.  
  166. from django.db import models
  167.  
  168. class Poll(models.Model):
  169.     question = models.CharField(max_length=200)
  170.     text = models.CharField(max_length=200, null=True)
  171.     pub_date = models.DateTimeField('date published')
  172.     yes = models.IntegerField(default=0)
  173.     no = models.IntegerField(default=0)
  174.  
  175.     def __unicode__(self):  # Python 3: def __str__(self):
  176.         return self.question
  177.  
  178.     def get_absolute_url(self):
  179.         return u"/polls/%s/" % self.pk
  180.  
  181.  
  182.  
  183. **********************************************
  184. models.py
  185. **********************************************
  186.  
  187. from django.conf.urls import patterns, url
  188.  
  189. from polls import views
  190.  
  191. urlpatterns = patterns('polls.views',
  192.     url(r'^$', views.index, name='index'),
  193.     url(r'^vote/(?P<poll_id>\d+)/$', views.vote, name='vote'),
  194.     url(r'^ajax_vote/(?P<poll_id>\d+)/$', views.ajax_vote, name='vote'),
  195.     url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
  196. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement