gpt4 book ai didi

python - 尝试在 Django Post LIKE DISLIKE 功能上使用 Ajax 时出现页面未找到错误

转载 作者:行者123 更新时间:2023-12-01 09:01:01 24 4
gpt4 key购买 nike

我的应用程序中有一个 Django Post Like/Dislike 功能。该功能本身效果惊人。然而,当我将 ajax 添加到“喜欢/不喜欢”按钮时,整个事情都会中断,给我一个“找不到页面”错误

不使用 Ajax 的工作代码

Models.py

class Post(models.Model): #title, slug, message, etc exist but not included here 
likes = models.ManyToManyField(User, blank=True, related_name='post_likes')

def get_absolute_url(self):
return reverse('posts:single', kwargs={'username': self.user.username,
'slug': self.slug})

def get_api_like_url(self):
return reverse('posts:like_post', kwargs={'username': self.user.username,
'slug': self.slug})

Views.py

class PostLikeToggle(LoginRequiredMixin, RedirectView):
def get_redirect_url(self, *args, **kwargs):
slug = self.kwargs.get('slug')
print(slug) #Prints the slug
obj = get_object_or_404(Post, slug=slug)
url_ = obj.get_absolute_url()
user = self.request.user
if user.is_authenticated():
if user in obj.likes.all():
obj.likes.remove(user)
else:
obj.likes.add(user)
print(url_)
return url_

模板:

<form action="{{post.get_api_like_url}}" method="post">
{% csrf_token %}
{% if user in post.likes.all %}
<button type="submit" name="post_slug" value="{{ post.slug }}" class="btn btn-link like_button">
<img class="like_heart" src="{% static 'images/HEART.RED.png' %}" height="25px">
</button>
{% else %}
<button type="submit" name="post_slug" value="{{ post.slug }}" class="btn btn-link like_button">
<img class="like_heart" src="{% static 'images/HEART.png' %}" height="25px">
</button>
{% endif %}

</form>

Urls.py

url(r'^(?P<username>[-\w]+)/(?P<slug>[-\w]+)/like_post/$', views.PostLikeToggle.as_view(), name="like_post")
  • 以上一切都完美运行

我添加了 Ajax。 下面是我添加 AJAX 后的代码,我发现页面未找到

模板与上面相同

型号与上面相同

网址与上面相同

Views.py

class PostLikeToggle(LoginRequiredMixin, RedirectView):
def get_redirect_url(self, *args, **kwargs):
slug = self.kwargs.get('slug')
print(slug)
obj = get_object_or_404(Post, slug=slug)
user = self.request.user
if user.is_authenticated():
if user in obj.likes.all():
obj.likes.remove(user)
else:
obj.likes.add(user)
context = {
"post": obj,

}
if self.request.is_ajax():
html = render_to_string("posts/like_section.html", context, request=self.request)
print(html) #This prints the html
print(JsonResponse({"form": html})) #This prints <JsonResponse status_code=200, "application/json">
return JsonResponse({"form": html})

已将脚本添加到 base.html

<script>
$(document).ready(function () {
$(".like_button").click(function (event) {
event.preventDefault();
var slug = $(this).attr("value"); #I have tried console.logging slug it works
$.ajax({
url : "{{post.get_api_like_url}}",
type: "POST",
data: {"slug": slug, "csrfmiddlewaretoken": "{{ csrf_token }}"},
dataType: "json",
success: function (data) {
$("#like-section").html(data["form"]);
console.log($("#like-section").html(data["form"]));
}, error: function (rs, e) {
console.log("error");
console.log(rs, e);
}
})
})
})
</script>

Terminal prints everything in the view with print and then gives the below

: [24/Sep/2018 00:23:10] "POST /posts/charlize/singes-boat-new-york/like_post/ HTTP/1.1" 302 0

Not Found: /posts/charlize/singes-boat-new-york/like_post/ [24/Sep/2018 00:23:10] "GET /posts/charlize/singes-boat-new-york/like_post/%3CJsonResponse%20status_code=200,%20%22application/json%22%3E HTTP/1.1" 404 7845

enter image description here

仅供引用:如果我手动刷新页面,“喜欢/不喜欢”切换功能就会起作用

最佳答案

您正在实现 get_redirect_url 方法。无论该方法返回什么,我们都会将其视为将浏览器重定向到的 URL。 JsonResponse 函数返回一个包含响应数据的对象。但由于这是 get_redirect_url,Django 认为它是一个带有 URL 的字符串。

相反,实现 post 方法,如果是普通请求,则手动返回 HttpResponseRedirect,如果是 AJAX,则手动返回 JsonResponse请求。

另一件事:您正在使用 LoginRequiredMixin mix-in。无需在 View 中检查 user.is_authenticated

class PostLikeToggle(LoginRequiredMixin, RedirectView):
def post(self, *args, **kwargs):
slug = self.kwargs.get('slug')
obj = get_object_or_404(Post, slug=slug)
user = self.request.user
context = {"post": obj}

if user in obj.likes.all():
obj.likes.remove(user)
else:
obj.likes.add(user)

if self.request.is_ajax():
html = render_to_string("posts/like_section.html", context, request=self.request)
return JsonResponse({"form": html})

url = obj.get_absolute_url()
return HttpResponseRedirect(url)

关于python - 尝试在 Django Post LIKE DISLIKE 功能上使用 Ajax 时出现页面未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52456154/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com