我正在为文章添加书签。我想在单击“添加到书签”按钮时将文章添加到书签中。
使用 Django,传统的做法是通过传递文章的 slug 来重定向到书签页面,并处理 views.py
中的信息。
目前,在views.py
中的书签页面功能下,我有一组代码将文章保存到当前用户的书签对象中,
user_instance = get_object_or_404(User,username = request.user.username)
userprofile_instance = get_object_or_404(UserProfile,user = user_instance)
new_readlater = Bookmarks.objects.get_or_create(user = userprofile_instance, article_slug = slug)
哪里,
User
是内置的 Django 用户。UserProfile
是扩展的User
模型。Bookmarks
是与UserProfile
的OneToMany关系。class Bookmarks(models.Model): user = models.ForeignKey(UserProfile, default = 1) read_later = models.CharField(default = "", max_length = 120)
我知道,可以通过重定向到书签页面 URL 来调用书签功能,从而可以保存书签。但我不想重定向到书签页面,而是想将其添加到文章页面本身。如何调用相同的书签保存函数来处理按钮单击时的书签信息?
最佳答案
如果我理解你的问题,你需要做的是在网页中提交按钮时进行 ajax POST 调用:
$.ajax({
url: "url_to_call",
type: "POST",
data: { csrfmiddlewaretoken: "{{ csrf_token }}", //django needs this
data_item: mydata},
timeout:0,
success: function(data){//do something when done
//data will be the string returned by HTTPResponse
}
}
并在你的views.py中返回一个HTTPResponse
response = HttpResponse("Here is some data to send back to the webpage")
这将使您保持在同一页面上,而无需重定向
关于javascript - 如何调用 Django 函数而不重定向到新页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43003136/