【发布时间】:2020-06-20 01:20:26
【问题描述】:
我正在构建一个博客,用户可以点击侧边栏中的多个<li> 项目以根据点击的类别显示博客文章。
想要的结果有点像官方的documentation,所以我最终会得到/blog/category 和相应的博客文章。
问题是如果我访问主页(或开发中的http://127.0.0.1:8000/)会引发错误
render_blog() missing 1 required positional argument: 'category'
那么,如何将视图 render_blog 用于主页和单击的类别以呈现相应的博客文章?
html
<li class="navigation-item" id="spotlights-item">
<div id="spotlights-ctn"><a href="/HotStocks">Hot Stocks</a><img id="fire-icon" src="{% static 'images/fire.svg' %}" alt="finsphere.io"></div>
</li>
网址
urlpatterns = [
path('AsiaPacific/<category>', render_blog, name='AsiaPacific'),
url(r'^$', render_blog, name='render_blog'),
]
views.py
def render_blog(request, category):
category = category
if not category:
# Main blog as landing page
# Get 5 latest posts and order by publish date, newest first
posts = Post.objects.filter(publish_date__lte=now).order_by('-publish_date')[:5]
return render(request, 'blog/blog.html', {'posts': posts})
else:
# Blog displayed as Category Selection
posts = Post.objects.filter(categories__title=category, publish_date__lte=now)
return render(request, 'blog/blog.html', {'posts': posts})
【问题讨论】:
-
嗨,我有一个建议。为什么你不能通过 href load more 传递变量(加载更多链接)在你的情况下在 ajax 中传递值,并使用查看条件检查如果。这是可能的,对吧?无需每次都编写新函数。这只是一个建议。
-
@SaranPrasad 感谢您的意见,但我无法理解您的想法:-x
-
您需要在 ajax 调用中传递一个变量并检查视图中的变量值。您正在维护不同的 html 页面,对吗?所以你很容易做到了。在类别部分 ajax 调用传递一个值,如类别。您需要在加载函数中识别此类别,使用 if 条件重定向 it 类别模型集。
-
但是初始查询集不是基于ajax的,那么如何在单击锚标记链接时将变量传递给视图?