Reputation: 2249
I am trying to setup a button on my website that when clicked a new model item is saved to the database. Segments of my code are pasted below and I will discuss the problem after.
textbook.html
<script src="../../static/textchange/wishlisting.js"></script>
...
<input type="button" id="addwishlist" value="Add to Wishlist"></input>
wishlisting.js
$('#addwishlist').click(function() {
$.ajax({
url: '/textbook/',
method: 'POST', // or another (GET), whatever you need
data: {
name: request.user,
book: text, // data you need to pass to your function
click: True
}
success: function (data) {
// success callback
// you can process data returned by function from views.py
}
});
});
views.py
def textbook(request, uisbn):
form4 = AddWishlist(request.POST or None)
ltextbook = Textbook.objects.filter(isbn = uisbn)
text = ltextbook[0]
wishlists = Wishlist.objects.filter(textbook = text)
listings = Posting.objects.filter(textbook = text)
if request.POST.get('click', False):
new = Wishlist(textbook = text, user = name, wish_date = datetime.now())
new.save()
From my understanding when I click the "Add to Wishlist" button it should correlate that id with the id of the jquery referenced in wishlisting.html and then the view should be loaded and the database item should be made. What am I missing in my thought process?
Thanks.
Upvotes: 2
Views: 1370
Reputation: 2901
Some changes to begin:
1.) Use staticfiles
to load files in templates:
{% load staticfiles %}
# You might need to change the path
<script type="text/javascript" src="{% static 'textchange/wishlisting.js' %}"></script>
2.) Get used to CamelCase:
<input type="button" id="addWishList" value="Add to Wishlist" uisbn="set_value_here"></input>
To answer your question:
views.py:
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.http import require_http_methods
from datetime import datetime
@require_http_methods(['POST'])
def textbook(request):
uisbn = request.POST.get('uisbn')
# I'm assuming all of this is correct
ltextbook = get_object_or_404(Textbook, isbn=uisbn)
if ltextbook:
text = ltextbook[0]
wishlists = Wishlist.objects.filter(textbook=text)
listings = Posting.objects.filter(textbook=text)
new = Wishlist(textbook=text, user=request.user, wish_date=datetime.now())
new.save()
new_created = True
else:
new_created = False
data = {
'new_created': new_created
}
return JsonResponse(data)
html:
$('#addWishList').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
// Use the name of the url not '/textbook/'
url: "{% url 'textbook' %}",
data: {
"uisbn": $(this).attr("uisbn"),
csrfmiddlewaretoken: "{{ csrf_token }}",
},
dataType: "json",
success: function(data) {
if (data.new_created) {
// Do something here
} else {
// Do something else here
}
},
error: function (rs, e) {
alert('Sorry, there was an error.');
}
});
});
Upvotes: 1