【问题标题】:How to use string of <li> in django view?如何在 django 视图中使用 <li> 字符串?
【发布时间】:2020-06-20 01:20:26
【问题描述】:

我正在构建一个博客,用户可以点击侧边栏中的多个&lt;li&gt; 项目以根据点击的类别显示博客文章。

想要的结果有点像官方的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的,那么如何在单击锚标记链接时将变量传递给视图?

标签: python html django ajax


【解决方案1】:

我不是 100% 确定我在关注,但您不必使用锚标记上的 href 来链接任何地方。您可以设置 href="" 并给每个链接一个类,例如“category-link”。然后将您的 ajax onclick 事件绑定到该类,并让代码首先从链接中提取文本或其他属性并将其作为变量提交:

$('.category-link').on('click', function() {
  var link = $(this);
  var page = link.data('page');
  var category = link.data('category');
  $.ajax({
      type: 'post',
      url: '/lazy_load_posts/',
      data: {
         'page': page,
         'category': category,
         'csrfmiddlewaretoken': window.CSRF_TOKEN // from blog.html
      },
  (...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2014-09-09
    • 1970-01-01
    • 2019-11-20
    • 2015-01-27
    相关资源
    最近更新 更多