简体   繁体   English

找不到页面404 No Blog匹配给定查询

[英]Page not found 404 No Blog matches the given query

Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/like/?csrfmiddlewaretoken=UJ6I7mm2cjjSXK0MeuOLqm4E7OfMKTKtO461mCAsnTPdXT0UVw1z3JfMqijyIJAM&blog_id= Raised by: blog.views.like_post 找不到页面(404)请求方法:GET请求URL: http : //127.0.0.1 :8000/like/?csrfmiddlewaretoken=UJ6I7mm2cjjSXK0MeuOLqm4E7OfMKTKtO461mCAsnTPdXT0UVw1z3JfMqijyIJAM&blog_id=s引发:

No Blog matches the given query. 没有博客与给定查询匹配。


I was making a like section for my blog app and this error is displayed below are my views, models and urls files 我在为博客应用程序创建一个喜欢的部分,并且此错误显示在下面,这是我的视图,模型和url文件


views.py views.py

from django.shortcuts import render,get_object_or_404
from django.views.generic import ListView
from .models import Blog

class BlogsList(ListView):
    model=Blog
    template_name='blog/home.html'
    context_object_name='blogs'
    ordering=['-date_posted']



def like_post(request):
    post= get_object_or_404(Blog, id=request.POST.get('blog_id'))
    post.likes.add(request.user)
    return HttpResponseRedirect(Blog.get_absolute_url())

models.py models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse 

class Blog(models.Model):
    title=models.CharField(max_length=100)
    content=models.TextField()
    date_posted=models.DateTimeField(default=timezone.now)
    author=models.ForeignKey(User, on_delete=models.CASCADE)
    likes=models.ManyToManyField(User,related_name='likes',blank=True)
    def __str__(self):
        return self.title

urls.py urls.py

from django.urls import path
from . import views 
from django.conf.urls import url

urlpatterns=[
path('',views.BlogsList.as_view(),name='blog-home'),
url(r'^like/$', views.like_post, name='like_post')
]

Your view function like_post is the culprit here. 您的视图函数like_post是这里的元凶。

The like_post should be called with a POST method and passed a request parameter blog_id . 应该使用POST方法调用like_post ,并传递一个请求参数blog_id I don't see where do you do this. 我看不到你在哪里做。

I suggest you to rewrite the view function: 我建议您重写视图函数:

def like_post(request, blog_id):
    post = get_object_or_404(Blog, id=blog_id)
    # the rest can stay unchanged

and in the urls.py change the following line: 并在urls.py更改以下行:

url(r'^like/$', views.like_post, name='like_post')

to: 至:

path('<int:blog_id>/like/', views.like_post, name='like_post')

Mixing the new path and the old url doesn't look very nice to me. 对我来说,将新path和旧url混在一起看起来并不好。 Now you can pass the blog_id in the URL and the view will take care to return 404 NOT FOUND if a blog doesn't exist. 现在,您可以在URL中传递blog_id ,如果博客不存在,视图将注意返回404 NOT FOUND。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM