【问题标题】:Page not found (404): No Post matches the given query.找不到页面(404):没有帖子与给定的查询匹配。
【发布时间】:2018-04-30 07:33:51
【问题描述】:

我正在尝试在帖子上创建一个“喜欢”按钮。帖子属于一个组。但是,在我的视图函数中,我收到 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'),
]

(post/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>

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

【问题讨论】:

    标签: python django django-models django-templates django-views


    【解决方案1】:

    您似乎将组 ID 传递给 POST 请求:{% url 'posts:like' group.id %} 而不是 Post id。

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

    【讨论】:

      猜你喜欢
      • 2016-07-25
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2019-12-23
      • 2021-09-18
      • 2019-07-21
      • 1970-01-01
      相关资源
      最近更新 更多