簡體   English   中英

Django:將變量從 get_context_data() 傳遞到 post()

[英]Django: Passing variable from get_context_data() to post()

該變量在get_context_view()定義,因為它需要一個id來訪問正確的數據庫對象:

class FooView(TemplateView):
  def get_context_data(self, id, **kwargs):
    ---
    bar = Bar.objects.get(id=id)
    ---

  def post(self, request, id, *args, **kwargs):
    # how to access bar?
    # should one call Bar.objects.get(id=id) again?

bar變量傳遞給post()什么?

試圖將其保存為self.bar的字段並通過self.bar訪問它,但這並不能解決問題。 post()看不到self.bar

你應該扭轉它。 如果你需要在post() bar ,你需要在那里創建它:

class FooView(TemplateView):
    def get_context_data(self, **kwargs):
        bar = self.bar

    def post(self, request, id, *args, **kwargs):
        self.bar = Bar.objects.get(id=id)
        ...

post()get_context_data之前被調用,這就是為什么如果你在get_context_data定義post就看不到它。

正如 knbk 所說,我的解決方案是 dispatch 方法,在那里我定義了我將在 get_context_data 和 post 方法中使用的變量,這對我來說是在我的示例中共享數據的一種方式

def dispatch(self, request, *args, **kwargs):

    self.some_data = '123'
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get_context_data(self, **kwargs):
    context = super(MyTestCreateView, self).get_context_data(**kwargs)
    print('test get_context_data', self.some_data)

def post(self, request, *args, **kwargs):        
    print('test post', self.some_data)
    return super().post(request, *args, **kwargs)

經典的 CBV我希望它有幫助

如果在您的 CBV(基於類的視圖)中定義了該變量,則可以直接在您的模板中調用它。

視圖.py

class SomeRandomView(FormView):
    username = 'SomeValue'

模板.html

<p>Username is {{view.username}}<p>

旁注:如果我沒記錯的話,您甚至可以直接在 Django 1.5 版之后的模板文件中調用視圖類中的方法。

我知道為時已晚,但幾天前我遇到了同樣的問題。 但是,這是我的解決方案。

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['foos'] = self.object.filter()
    return context

def post(self, request, *args, **kwargs):
    context = super().post(request, *args, **kwargs)
    foos = self.get_context_data().get('foos')
    # do stuff here
    return context

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM