找不到页面(404):没有帖子与给定的查询匹配。

时间:2018-04-30 07:33:52

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

我正在尝试创建一个' Like'一个帖子上的按钮。一个帖子属于一个组。但是,在我的视图功能中,我收到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})

(groups / detail 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>

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

1 个答案:

答案 0 :(得分:0)

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

而是使用表单发送POST请求,使用XHRFetch