【问题标题】:why only one variable or form passing to the template django为什么只有一个变量或表单传递给模板 django
【发布时间】:2020-07-06 19:34:01
【问题描述】:

我的表单正在传递,但品牌没有传递 这是我的意见。py

class index(View):
template_name = 'homepage/columntemplate.html'
#form_class = MyForm

def get(self, request,*args, **kwargs):
    #for _ in range (10):
    #        value = randint(0,10)

    brand = Brand.objects.get(pk=randint(1,2))
    brand_listing ={'brand' : brand}
    return render(request, self.template_name, brand_listing)


def get(self, request, *args, **kwargs):
    form = Search(request.GET or None)
    if form.is_valid():
            form.save()
    content = {'form' : form}
    return render(request, self.template_name, content)

我的模板有两个标签 {{brand}} 和 {{form}}

【问题讨论】:

    标签: python html django templates variables


    【解决方案1】:

    您需要添加 get_context_data 方法将值从视图传递到模板。像这样的

    class index(FormView):
        template_name = 'homepage/columntemplate.html'
        form_class = MyForm
    
        def get(self, request, *args, **kwargs):
            # you can add your code here which will execute on page load
            return super().get(request, *args, **kwargs)
    
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            brand = Brand.objects.get(pk=randint(1,2))
            brand_listing ={'brand' : brand}
            # you can add more such parameters you want to pass to the template
            # and you can use it like {{brand}}
            # and can also use {{form}} in the template if you define form_class (all fields from form can be accessed)
            context['brand'] = brand
            return context
    
        def post(self, request, *args, **kwargs):
            #  form = Search(request.GET or None)
            form = self.get_form()
            if form.is_valid():
                # define save method in your Form "MyForm"
                form.save()
            content = {'form' : form}
            return render(request, self.template_name, content)
    

    希望这会有所帮助。

    干杯!

    【讨论】:

      猜你喜欢
      • 2019-04-03
      • 2013-03-06
      • 2018-12-26
      • 2014-11-30
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 2011-03-04
      • 2018-12-03
      相关资源
      最近更新 更多