1

I'm an absolute beginner to django (and programming in general), I've tried the django Polls tutorial and all went well, however I am trying to get a minimal voting button to work. Basically I have set up a database with two columns, my models.py looks like this

from django.db import models


class Imgurl(models.Model):

    urlvar = models.URLField(max_length=200)# a URL linking to an image
    urlvote = models.IntegerField(default=0)# my intended vote count

    def __unicode__(self):
        return self.urlvar

I have made an input box where I can copy and paste an image url, this image then displays on a separate page(this works fine). What I want is to have a voting button next to each displayed image, where a user can click on the button (I am trying to use a submit button) and the number of votes will increase in the db(no redirecting to a new page, or anything fancy).

I think this is a trivial question and I am trying to learn the basics of POST and database handling in django (also, I have read the relevant chapters in the djangobook... maybe I'm just a little slow?)

my views looks like this

def urlvotes(request):

    if request.method=='POST':
        if 'voteup' in request.POST:
            v=Imgurl(forloop.counter)
            v.urlvote +=1
        else:
            pass
        votetotal=v.urlvote # attempt to give the template some kind of context
    return render_to_response('display.html', {'votetotal':votetotal}, context_instance=RequestContext(request))

and my template looks like this:

{% extends "base.html" %}

{% block head %}Image display{% endblock %}
{% block content1 %}

<a href="http://127.0.0.1:8000/home/">Home</a>
{% if links %}
        <ul>
        {% for link in links %}
            <li><img src="{{ link }}"></li>

            <li><form action="{% url urlvotes %}" method="post"> 
            {% csrf_token %}
            <input type="submit" name="voteup" value='vote'/></p>
            <p>{{votetotal}}</p>
            </form></li>

        {% endfor %}

        </ul>
{% else %}
<p>No uploads.</p>
{% endif %}
{% endblock %}

when I run this, as is, I get a csrf verification failed error

Any help would be greatly appreciated

okm
  • 23,575
  • 5
  • 83
  • 90
  • This sounds very much like this problem: http://stackoverflow.com/questions/4547639/django-csrf-verification-failed – schacki Oct 05 '12 at 13:01
  • nitpick: use `/home/` w/o full ip:port in `Home`. (ignore this if you intend that) – okm Oct 05 '12 at 13:19

1 Answers1

0

Try adding the @csrf_protect to your view

@csrf_protect
def urlvotes(request):

    if request.method=='POST':
        if 'voteup' in request.POST:
            v=Imgurl(forloop.counter)
            v.urlvote +=1
    else:
        pass
    votetotal=v.urlvote # attempt to give the template some kind of context
    return render_to_response('display.html', {'votetotal':votetotal}, context_instance=RequestContext(request))
Krazzzeee
  • 76
  • 4