【问题标题】:django object data disappears when I refresh page当我刷新页面时,django 对象数据消失了
【发布时间】:2017-10-24 19:34:35
【问题描述】:

当我第一次加载页面时,在我的计算机上启动 runserver 后,对象数据就在那里(下面示例中的三个链接)。如果我重新加载对象数据不再存在(所以下面示例中的链接为零)。

模板

{% for url in urls %}
   <a href="{{ url }}">
      link
   </a>
{% endfor %}

查看

class IntroView(View):

    template_name = '[app_name]/template.html'
    model_names = ['shoe', 'hat', 'bag']
    urls = [reverse_lazy('%s:%s' % ('[app_name]', name)) for name in model_names]
    dict_to_template = {'urls': urls}

    def get(self, request, *args, **kwargs):
        return render(request, self.template_name, context=self.dict_to_template)

这可能很简单,但它抓住了我。

感谢您的宝贵时间。

【问题讨论】:

    标签: django


    【解决方案1】:

    我认为您的示例无法解释您所看到的行为。

    如果您使用生成器表达式而不是列表推导式,那么您将收到该错误,因为生成器将在视图第一次运行时被消耗。

    class IntroView(View):
        template_name = '[app_name]/template.html'
        model_names = ['shoe', 'hat', 'bag']
    
        urls = (reverse_lazy('%s:%s' % ('[app_name]', name)) for name in model_names)
        dict_to_template = {'urls': urls}
    
        def get(self, request, *args, **kwargs):
            return render(request, self.template_name, context=self.dict_to_template)
    

    您可以通过将代码移动到get() 方法中来避免该问题,这样每次视图运行时它都会运行。

    class IntroView(View):
        template_name = '[app_name]/template.html'
        model_names = ['shoe', 'hat', 'bag']
    
        def get(self, request, *args, **kwargs):
            urls = (reverse_lazy('%s:%s' % ('[app_name]', name)) for name in model_names)
            dict_to_template = {'urls': urls}
            return render(request, self.template_name, context=dict_to_template)
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 2022-12-05
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多