posts.models.blog.doesnotexist:不存在博客匹配查询
我正在尝试使用Slug进行导航。这是html标签
<a href="{% url 'blog_details' blog.slug|slugify %}">Read More</a>
urls.py
path('details/<slug:slug>/', views.blog_details, name='blog_details'),
型号。
slug= models.SlugField(max_length=264,unique=True,null=True,allow_unicode=True)
这是我创建自动slug的方式,
def Creating_blog(request):
form=BlogForm()
if User.is_authenticated:
if request.method=='POST':
form=BlogForm(request.POST,request.FILES)
if form.is_valid:
blog_obj=form.save(commit=False)
blog_obj.author=request.user
title=blog_obj.blog_title
blog_obj.slug = title.replace(' ','-') + '-'+ str(uuid.uuid4())
blog_obj.save()
return redirect('index')
return render(request,'blogs/creatingblog.html',context={'form':form})
这是博客详细信息页面的视图,
def blog_details(request, slug):
if User.is_authenticated:
blog = Blog.objects.get(slug=slug)
already_liked = Likes.objects.filter(blog=blog, user= request.user)
if already_liked:
liked = True
else:
liked = False
comments=Comment.objects.filter(blog=blog)
commet_form=CommentForm()
if request.method=='POST':
commet_form=CommentForm(request.POST)
if commet_form.is_valid():
comment=commet_form.save(commit=False)
comment.user=request.user
comment.blog=blog
comment.save()
return HttpResponseRedirect(reverse('blog_details',kwargs={'slug':slug}))
return render(request,'blogs/blogdetails.html',context={'blog':blog,'comment_form':commet_form,'comments':comments,'like':liked})
else:
HttpResponseRedirect(reverse('login'))
必须出现问题
C:\Users\ITS\Desktop\blogger\Blog\posts\views.py, line 51, in blog_details
blog = Blog.objects.get(slug=slug)
如果我使用pk = id而不是slug,则 。但是,每当我试图用slug抓住错误时,错误就会上升。我在这里呆了几天,我找不到问题。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过将slag通过 /code> 模板过滤器&nbsp; [django-doc] 它可能会转换一些sl,因此不再可能链接到原始slug。您应该删除模板过滤器,然后使用:
但是,无论如何,不是不是一个好主意。您可以使用django's 函数&nbsp; [django-doc] 进行正确的操作。该视图还包含一些问题,例如
user.is_authenticated
将始终具有真实性true
,因此永远不会失败,.is_valid()
&nbsp; < sup> [django-doc] 是一种方法,因此您需要 call this:By passing the slug through the
|sligify
template filter [Django-doc] it might transform some slugs, such that linking to the original slug is no longer possible. You should remove the template filter, and work with:But regardless, slugifying yourself is not a good idea. You can use Django's
slugify(…)
function [Django-doc] to do this properly. The view also contains some problems, for exampleUser.is_authenticated
will always have truthinessTrue
, and thus never fail, and.is_valid()
[Django-doc] is a method, so you need to call this:终于有效。我刚刚做出了一些更改。 锚标签
更改此另一个错误后的
是我更改了urls.py
Finally it works. I have just made a little changes. The anchor tags
after changing this one other error was
i changed the urls.py