At the moment I have multiple 'Photo' objects being displayed on a pages template.
The Photo
Model has a field 'score' which has a default value of 0.
I am struggling to find a way to add two buttons ("up"/"down") in the template related to each object so when the "up" button is clicked it adds 1 to that particular Photo objects score, or if "down" is clicked it subtracts 1 from the score and once the button has been clicked it updates the photos score value in the database.
Here is an example of what I mean:
I have looked into using ModelForms and been through the django tutorial on forms but I am struggling to work out how to do it.
It should be very straightforward. The up/down vote button could be just a link that links to your view method with photo id in url. In your view method you take the photo id and search for corresponding photo, then update the score.
I provide a simple example here, you need to read django tutorial on how each detail works to complete it:
template.html:
{% for photo in photos %}
<a href="upvote/{{ photo.id }}">up</a>
{% endfor %}
urls.py
url(r'^upvote/(?P<photo_id>[0-9]+)/$', views.upvote, name='upvote'),
views.py
def upvote(request, photo_id):
photo = Photo.objects.get(pk=photo_id)
photo.score += 1
photo.save()
return HttpResponse('your-photo-list-view')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.