I really need some help with Ajax and Django! I'm trying to iterate over all Item objects so that each one has an individual form that allows the user to favorite the item with an ajax button.
Here is my form:
<div class="row">
{% for item in items%}
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
{% if item.photo %}
<img src="{{ MEDIA_URL }}{{item.photo.url}}">
{% endif %}
<div class="caption">
<h3>{{item.name}}</h3>
<p>{{item.description}}</p>
<h3>Price: {{item.price}}</h3>
<h3>Rating: {{item.rating}}</h3>
<p>
<form id="add_favorite_form">
{% csrf_token %}
<button id='fav' class='btn btn-primary' type="submit" data-itemid="{{item.id}}" value="Favorite">
Favorite
<span class="glyphicon glyphicon-thumbs-up"</span></a>
</form>
</p>
</div>
</div>
</div>
{% endfor %}
</div>
Here is the Ajax:
<script type="text/javascript">
$(document).on('submit', '#add_favorite_form',function(e){
e.preventDefault();
var $fav = $('#fav');
$.ajax({
type: "POST",
url: "/items/favorites/",
data: {
id: $($fav).attr('data-itemid'),
csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
},
success: function(){
alert("button works but is broken. Only the first Item instance is added to favorites")
}
});
});
</script>
And finally, my views:
def favorite_item(request):
favorites, created = Favorite.objects.get_or_create(user=request.user)
if request.method == "POST":
id = request.POST['id']
item = Item.objects.get(id=id)
print item
favorites.items.add(item)
favorites.save()
return HttpResponse(' ')
As you can see, the button uses {{item.id}} as the data-* attribute, so I assumed that this would pass the value of each individual item.id to the variable var $fav = $('#fav'); in the ajax script. However, only the first item.id ever seems to be passed because that is the only Item object that is added to favorites.
How can I solve this issue? Thanks for any help.
favas class instead of id{{ MEDIA_URL }}{{item.photo.url}}. If you configured yourMEDIA_ROOTandMEDIA_URLcorrectly,{{item.photo.url}}should suffice (Django will add the necessary base path).