gpt4 book ai didi

javascript - NoReverseMatch at/blog/in django 2.0

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:45 25 4
gpt4 key购买 nike

尝试设置博客类别页面时遇到此错误NoReverseMatch 位于/blog/找不到参数 '('',)' 的“category_detail”的反向操作。尝试了 1 个模式:['blog\/category\-detail\/(?P[-a-zA-Z0-9_]+)$']

这是我的 url.py

from django.urls import path,include
from .import views

urlpatterns = [
path('blog/',views.post_list,name="post_list"),
path('blog/post-detail/<slug:slug>',views.post_detail,name="post_detail"),
path('blog/category-detail/<slug:slug>',views.category_detail,name="category_detail"),

]

View .py

from django.shortcuts import render,get_object_or_404
from.models import Post,Category

# Create your views here.
def post_list(request):
object_list=Post.objects.all()
context={
'object_list': object_list,
}
return render(request,"blog.html",context)

def post_detail(request,slug=None):
post=get_object_or_404(Post,slug=slug)
context={
'post':post,
}
return render(request,"post_detail.html",context)

def category_detail(request,slug=None):
category=get_object_or_404(Category,slug=slug)
post=Post.objects.filter(category=category,status='Published')
context={
'category':category,
'post':post,
}
return render(request,"category_detail.html",context)

博客.html

{% for obj in object_list %}
{% if obj.status == 'Published' %}
<article>
<div class="embed-responsive embed-responsive-16by9">
<img src="images/blog1.jpg" alt="" />
</div>
<div class="post-content">

<h2>{{obj.title}}</h2>

<div>
{{obj.created}} Author {{obj.user}} <h4><a href="{% url 'category_detail' slug=post.category.slug %}">{{obj.Category}}</a></h4>
<hr/>
<p>{{obj.body}}</p>
<a class="mtr-btn button-navy ripple" href= "{% url 'post_detail' obj.slug %}">Continue reading →</a><br>
</div>
</article>
{% endif %}
{% endfor %}

category_detail.html

{% extends "base.html" %}
{% load static %}
{% block seo_title %}{{category.seo_title}}{% endblock %}
{% block seo_description %}{{category.seo_description}}{% endblock %}
{% block Content %}
<h2>{{category.title}}</h2>
<p>{{category.description}}</p>
{% for item in post %}
{{item.title}}
{{item.body|truncatechars:50}}
{% endfor %}
{% endblock Content %}

请注意,其他 VIEWS.PY 工作正常,只有 Category_detail 函数

最佳答案

正如错误所述,这里缺少参数。也许您需要将 {% url 'category_detail' slug=post.Category.slug %} 更改为 {% url 'category_detail' slug=obj.category.slug %}因为我在 blog.html 模板中没有看到任何 post 变量引用。

更新

您尚未共享您的模型代码,但我假设您的 Post 模型具有 Category 模型的外键,并且看起来像 Category=models.ForeignKey (类别)。所以你需要像这样更新 View :

def category_detail(request,slug=None):
category=get_object_or_404(Category,slug=slug)
post=Post.objects.filter(Category=category,status='Published')

关于javascript - NoReverseMatch at/blog/in django 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53369086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com