【问题标题】:Testing views in Django, need a hand在 Django 中测试视图,需要帮助
【发布时间】:2017-09-23 15:22:45
【问题描述】:

我正在尝试了解 django 的工作原理,但我对视图有疑问。

下面的代码

def post_list(request):
    posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'blog/post_list.html', {'posts': posts})

我理解字典,但我不知道为什么{'posts': posts} 是同一个单词的字典,并且值没有引号。

当我使用字典时,我会使用以下内容:

hello = {'my_key': 'this is text', 'my_key2': 2017 }

{'posts': posts},在这个例子中帖子显示了两次,第二次,我的意思是这个值没有引号。

谁能解释一下?

【问题讨论】:

  • 不知道为什么你认为这些有什么不同。引号中的第一个元素是键;第二个是价值。
  • 这和你已经知道的字典一模一样,"posts" 是键,posts 是值,过滤后的对象。键将是在模板中调用您的值的一种方式,也可以是render(request, 'blog/post_list.html', {'filtered_posts': posts})

标签: python django dictionary django-views


【解决方案1】:

当你使用这样的语法时:

hello = {'my_key': 'this is text', 'my_key2': 2017 }

这里key'my_key'value'this is text'

但在这里:

posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')

在这个posts中是一个变量,它有一些价值

context = {'posts':posts}

在这种情况下,key'posts'valueposts 变量的值

我希望它对你有意义。上面的每个人都试图说同样的话。

【讨论】:

    猜你喜欢
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 2022-12-21
    • 1970-01-01
    • 2013-10-15
    • 2021-01-06
    相关资源
    最近更新 更多