2017-10-24 7 views
0

私のコンピュータ上でrunserverを起動した後、最初にページを読み込むと、オブジェクトデータがそこにあります(下の例では3つのリンク)。オブジェクトをリロードすると、データはそこに存在しなくなります(下の例ではリンクがゼロになります)。ページを更新するとdjangoオブジェクトのデータが消えます

テンプレート

{% 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) 

これはおそらく、本当に簡単なものだが、それは私を持っています。

ありがとうございます。

答えて

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) 
関連する問題