Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- **********************************************
- views.py
- **********************************************
- from django.shortcuts import render, HttpResponseRedirect, \
- redirect, get_object_or_404
- from polls.models import Poll
- def index(request):
- polls = Poll.objects.all()
- # if request.method == 'POST':
- # if request.POST['answer-1']:
- # answer = Answer(
- # )
- # answer.save()
- # return HttpResponseRedirect('results')
- # else:
- context = {'polls': polls}
- return render(request, 'index.html', context)
- def detail(request, question_id):
- return HttpResponse("You're looking at question %s." % question_id)
- def vote(request, poll_id):
- p = get_object_or_404(Poll, pk=poll_id)
- if request.POST['choice'] == 'yes':
- p.yes += 1
- if request.POST['choice'] == 'no':
- p.no += 1
- p.save()
- return HttpResponseRedirect('/')
- def ajax_vote(request, poll_id):
- p = get_object_or_404(Poll, pk=poll_id)
- if request.POST['choice'] == 'yes':
- p.yes += 1
- if request.POST['choice'] == 'no':
- p.no += 1
- p.save()
- print 'AJAX'
- # import ipdb;
- # ipdb.set_trace();
- return HttpResponseRedirect(p.get_absolute_url())
- **********************************************
- index.html
- **********************************************
- {% extends 'base.html' %}
- {% block content %}
- <div class="container">
- <div class="clear"></div> -->
- {% for poll in polls %}
- <div class="clear"></div>
- <div class="container poll-box">
- <form action="{% url 'polls:vote' poll.id %}" method="post">
- {% csrf_token %}
- <div class="responsiveWrapper poll-item">{{ poll.text|safe }}</div>
- <div class="clear"> </div>
- <div class="yes">
- <input type="radio" name="choice" id="choice-yes-{{ poll.id }}" value="yes" class="yes">
- <label for="choice-yes-{{ poll.id }}">This is terrorism</label>
- </div>
- <div class="no">
- <input type="radio" name="choice" id="choice-no-{{ poll.id }}" value="no" class="no">
- <label for="choice-no-{{ poll.id }}">This is not terrorism</label><br />
- </div>
- <div class="clear"></div>
- <p id="vote-button"><input type="submit" value="Vote»" class="btn btn-primary btn-large" id="vote" /></p>
- </form>
- </div>
- {% endfor %}
- </div>
- </div>
- <script type="text/javascript">
- $(document).ready(function() {
- var create_vote = function() {
- var value = $("form input[name='choice']:checked").val();
- if (value != "")
- {
- var data = { choice:value };
- var args = { type:"POST", url:"/ajax_vote/2/", data:data, complete:create_vote_complete };
- $.ajax(args);
- }
- else
- {
- // We should display a helpful error message
- "Something wrong"
- }
- return false;
- };
- var create_vote_complete = function(res, status) {
- if (status == "success") {
- window.location.href = "/";
- }
- else
- {
- display_message(res.responseText, $(".message"));
- }
- }
- var display_message = function(msg, elem) {
- var msg_div = $('<div><p>'+msg+'</p></div>');
- elem.append(msg_div).fadeIn('slow').animate({opacity: 1.0}, 7000).fadeOut('slow',function() { msg_div.remove(); });
- };
- function getCookie(name) {
- var cookieValue = null;
- if (document.cookie && document.cookie != '') {
- var cookies = document.cookie.split(';');
- for (var i = 0; i < cookies.length; i++) {
- var cookie = jQuery.trim(cookies[i]);
- // Does this cookie string begin with the name we want?
- if (cookie.substring(0, name.length + 1) == (name + '=')) {
- cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
- break;
- }
- }
- }
- return cookieValue;
- }
- var csrftoken = getCookie('csrftoken');
- function csrfSafeMethod(method) {
- // these HTTP methods do not require CSRF protection
- return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
- }
- $.ajaxSetup({
- crossDomain: false, // obviates need for sameOrigin test
- beforeSend: function(xhr, settings) {
- if (!csrfSafeMethod(settings.type)) {
- xhr.setRequestHeader("X-CSRFToken", csrftoken);
- }
- }
- });
- $("#vote").click(create_vote);
- });
- </script>
- {% endblock %}
- **********************************************
- models.py
- **********************************************
- from django.db import models
- class Poll(models.Model):
- question = models.CharField(max_length=200)
- text = models.CharField(max_length=200, null=True)
- pub_date = models.DateTimeField('date published')
- yes = models.IntegerField(default=0)
- no = models.IntegerField(default=0)
- def __unicode__(self): # Python 3: def __str__(self):
- return self.question
- def get_absolute_url(self):
- return u"/polls/%s/" % self.pk
- **********************************************
- models.py
- **********************************************
- from django.conf.urls import patterns, url
- from polls import views
- urlpatterns = patterns('polls.views',
- url(r'^$', views.index, name='index'),
- url(r'^vote/(?P<poll_id>\d+)/$', views.vote, name='vote'),
- url(r'^ajax_vote/(?P<poll_id>\d+)/$', views.ajax_vote, name='vote'),
- url(r'^(?P<poll_id>\d+)/$', views.detail, name='detail'),
- )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement