首页 > 解决方案 > 找不到页面(404):没有帖子与给定的查询匹配。

问题描述

我正在尝试在帖子上创建一个“喜欢”按钮。帖子属于一个组。但是,在我的视图函数中,我收到 404 错误,因为它无法找到单个帖子,即使它在 URL 中。以下是相关文件:

(帖子/urls.py):

from . import views
from django.urls import path


app_name = 'posts'

urlpatterns = [
    path('create/<int:group_id>/', views.create, name='create'),
    path('edit/<int:group_id>/<int:post_id>/', views.edit, name='edit'),
    path('delete/<int:group_id>/<int:post_id>/', views.delete, name='delete'),
    path('like/<int:post_id>/', views.like, name='like'),
]

(帖子/views.py):

from django.shortcuts import render, get_object_or_404, redirect
from groups.models import Group
from .models import Post
from .forms import PostForm
from django.utils import timezone

 def like(request, post_id):
     post =  get_object_or_404(Post, pk= post_id)

     if request.method == 'POST':
        post.likes_total += 1
        return redirect('/groups/index' )
        # post.save()
    else:
        return render(request, 'groups/detail.html', {'group':group})

(组/详细 html)

{% for post in posts %}
        <h2>{{post.title}}</h2>
        <h5>{{post.body}}</h5>
        <p>{{post.pub_date_pretty}}</p>
        <p>{{post.author}}</p>
        <a href="{% url 'posts:edit' group.id post.id %}">Edit</a>
        <a href="{% url 'posts:delete' group.id post.id %}">Delete</a>
        <a href="javascript:{document.getElementById('like').submit()}"><button class="btn btn-primary"> Like ({{post.likes_total}})</button></a>
{% endfor %}

  <form method ='POST' id= 'like' action="{% url 'posts:like' group.id %}" >
    {% csrf_token %}
    <input type="hidden" >
  </form>

只是不明白为什么它无法抓住帖子。任何帮助将非常感激!

标签: pythondjangodjango-modelsdjango-templatesdjango-views

解决方案


看起来您正在将组 id 传递给 POST 请求:{% url 'posts:like' group.id %}而不是 Post id。

与其使用表单发送 POST 请求,不如使用XHRFetch


推荐阅读