我正在尝试在我的网站上设置一个按钮,当单击该按钮时,一个新的模型项目将保存到数据库中。我的代码段粘贴在下面,我将在之后讨论这个问题。
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
}
});
});
View .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()
根据我的理解,当我单击“添加到 Wishlist”按钮时,它应该将该 ID 与 wishlisting.html 中引用的 jquery 的 ID 相关联,然后应该加载 View 并创建数据库项目。我在思考过程中遗漏了什么?
谢谢。
请您参考如下方法:
开始的一些改变:
1.) 使用staticfiles 加载模板中的文件:
{% load staticfiles %}
# You might need to change the path
<script type="text/javascript" src="{% static 'textchange/wishlisting.js' %}"></script>
2.) 习惯 CamelCase:
<input type="button" id="addWishList" value="Add to Wishlist" uisbn="set_value_here"></input>
回答你的问题:
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.');
}
});
});
