如何在django中使用ajax,在不刷新页面的情况下传递模型对象并将其存储在数据库中?
How to use ajax in django, to pass the model object and store it in database without refreshing the page?
我正在用 Django 做一个小项目,因为我想在其中一个页面中添加一个最喜欢的按钮,以便在单击该按钮时它必须 return 模型对象并且它有存储在另一个数据库中以供参考,但它没有发生
这是我的
home/bookdetails.html
<!DOCTYPE html>
{% extends 'home/Base.html' %}
{% block title %} Book Details {% endblock %}
{% load staticfiles %}
<link rel="stylesheet" href="{{ STATIC_URL }}/home/css/heart.css">
<script src="{% static 'js/heart.css' %}"></script>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="{% static 'js/app.js' %}"></script>
{% block body %}
{% if error_message %}<p><strong> {{ error_message }} </strong></p>{% endif %}
<script type="text/javascript">
$(document).ready(function(){
$("#sub").click(function(event) {
var userbooks = '{{ userbooks }}';
$.ajax({
type: "GET",
url: "{% url 'home:favoriteAjax' %}"
data:{userbbooks:userbooks}
datatype:'json'
success: function() {
alert("successfully added to favorites")
}
}
});
});
});
</script>
<p>Book name:{{ userbooks.book_name }}</p><br>
<p>Book author:{{ userbooks.book_author }}</p><br>
<p>Book genre:{{ userbooks.book_genre }}</p><br>
<p>Book ISBN:{{ userbooks.book_ISBN }}</p><br>
<button type="submit" id="sub" onclick="changeText()">Favourite</button>
{% endblock %}
我的urls.py:
from django.urls import path
from . import views
app_name='home'
urlpatterns=[
path('',views.HomeView,name='home'),
path('addBooks/',views.addBooks,name='addBooks'),
path('myBooks/',views.BooksView.as_view(),name='myBooks'),
path('<int:pk>/', views.BookDetailsView.as_view(), name='myBooks'),
path('search/', views.SearchedBooks.as_view(), name='searchedBooks'),
path('favorite_ajax/', views.favorite_ajax, name='favoriteAjax'),
]
我的models.py:
from django.db import models
from django.contrib.auth.models import User
class UserBooks(models.Model):
user_id = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
username = models.CharField(max_length=200)
book_name = models.CharField(max_length=200)
book_author = models.CharField(max_length=200)
book_ISBN=models.CharField(max_length=200)
book_genre = models.CharField(max_length=200)
book_status=models.BooleanField(default=False)
class Meta:
unique_together = (("username", "book_ISBN"),)
def __str__(self):
return self.book_name
class FavBooks(models.Model):
user_id = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
book_id= models.ForeignKey(UserBooks,on_delete=models.CASCADE,null=True)
class Meta:
unique_together = (("user_id", "book_id"),)
我的views.py:
def favorite_ajax(request):
if(request.method=='GET'):
book=request.GET['userbooks']
fav=FavBooks()
fav.book_id=book
fav.user_id=request.user
fav.save()
return HttpResponse("done")
我想从 bookdetails.html 到 ajax 调用中获取 userbooks 模型对象,并希望将该引用存储在 FavBooks 模型中。我怎样才能让它发生?谢谢!
这是正确的做法:
html:
<form id="form_id" method='post'>{% csrf_token %}
<button type="submit">Favourite</button>
</form>
jQuery:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var userbooks = '{{ userbooks }}';
$.ajax({
type: "POST",
url: "{% url 'home:favoriteAjax' %}",
data:{
userbooks:userbooks,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
alert("successfully added to favorites")
}
});
});
views.py:
from django.http import JsonResponse
def favorite_ajax(request):
data = {'success': False}
if request.method=='POST':
book = request.POST.get('userbooks')
fav = FavBooks()
fav.book_id = book
fav.user_id = request.user
fav.save()
data['success'] = True
return JsonResponse(data)
我正在用 Django 做一个小项目,因为我想在其中一个页面中添加一个最喜欢的按钮,以便在单击该按钮时它必须 return 模型对象并且它有存储在另一个数据库中以供参考,但它没有发生 这是我的 home/bookdetails.html
<!DOCTYPE html>
{% extends 'home/Base.html' %}
{% block title %} Book Details {% endblock %}
{% load staticfiles %}
<link rel="stylesheet" href="{{ STATIC_URL }}/home/css/heart.css">
<script src="{% static 'js/heart.css' %}"></script>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="{% static 'js/app.js' %}"></script>
{% block body %}
{% if error_message %}<p><strong> {{ error_message }} </strong></p>{% endif %}
<script type="text/javascript">
$(document).ready(function(){
$("#sub").click(function(event) {
var userbooks = '{{ userbooks }}';
$.ajax({
type: "GET",
url: "{% url 'home:favoriteAjax' %}"
data:{userbbooks:userbooks}
datatype:'json'
success: function() {
alert("successfully added to favorites")
}
}
});
});
});
</script>
<p>Book name:{{ userbooks.book_name }}</p><br>
<p>Book author:{{ userbooks.book_author }}</p><br>
<p>Book genre:{{ userbooks.book_genre }}</p><br>
<p>Book ISBN:{{ userbooks.book_ISBN }}</p><br>
<button type="submit" id="sub" onclick="changeText()">Favourite</button>
{% endblock %}
我的urls.py:
from django.urls import path
from . import views
app_name='home'
urlpatterns=[
path('',views.HomeView,name='home'),
path('addBooks/',views.addBooks,name='addBooks'),
path('myBooks/',views.BooksView.as_view(),name='myBooks'),
path('<int:pk>/', views.BookDetailsView.as_view(), name='myBooks'),
path('search/', views.SearchedBooks.as_view(), name='searchedBooks'),
path('favorite_ajax/', views.favorite_ajax, name='favoriteAjax'),
]
我的models.py:
from django.db import models
from django.contrib.auth.models import User
class UserBooks(models.Model):
user_id = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
username = models.CharField(max_length=200)
book_name = models.CharField(max_length=200)
book_author = models.CharField(max_length=200)
book_ISBN=models.CharField(max_length=200)
book_genre = models.CharField(max_length=200)
book_status=models.BooleanField(default=False)
class Meta:
unique_together = (("username", "book_ISBN"),)
def __str__(self):
return self.book_name
class FavBooks(models.Model):
user_id = models.ForeignKey(User,on_delete=models.CASCADE,null=True)
book_id= models.ForeignKey(UserBooks,on_delete=models.CASCADE,null=True)
class Meta:
unique_together = (("user_id", "book_id"),)
我的views.py:
def favorite_ajax(request):
if(request.method=='GET'):
book=request.GET['userbooks']
fav=FavBooks()
fav.book_id=book
fav.user_id=request.user
fav.save()
return HttpResponse("done")
我想从 bookdetails.html 到 ajax 调用中获取 userbooks 模型对象,并希望将该引用存储在 FavBooks 模型中。我怎样才能让它发生?谢谢!
这是正确的做法:
html:
<form id="form_id" method='post'>{% csrf_token %}
<button type="submit">Favourite</button>
</form>
jQuery:
$("#form_id").on('submit', function(event) {
event.preventDefault();
var userbooks = '{{ userbooks }}';
$.ajax({
type: "POST",
url: "{% url 'home:favoriteAjax' %}",
data:{
userbooks:userbooks,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
alert("successfully added to favorites")
}
});
});
views.py:
from django.http import JsonResponse
def favorite_ajax(request):
data = {'success': False}
if request.method=='POST':
book = request.POST.get('userbooks')
fav = FavBooks()
fav.book_id = book
fav.user_id = request.user
fav.save()
data['success'] = True
return JsonResponse(data)