【问题标题】:Django - Passing a variable from Class Based Views to TemplateDjango - 将变量从基于类的视图传递到模板
【发布时间】:2021-03-31 20:50:24
【问题描述】:

在基于函数的视图中,我可以像这样传递变量:

def zip(request):

    check_for_zipcode = request.user.profile.location

    zipcodes = {
        'check_for_zipcode' : check_for_zipcode
    }
    return render(request, 'front/post_form.html',  zipcodes)

然后我就可以在我的 HTML 中访问check_for_zipcode。但是我将如何在基于类的视图中做到这一点?假设我有以下基于类的视图。

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content', 'post_image', 'title2', 'content2', 'post_image2']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

我如何将check_for_zipcode = request.user.profile.location 传递到基于类的视图中?

【问题讨论】:

    标签: python django django-views django-templates


    【解决方案1】:

    您可以在 get_context_data 方法中编辑上下文数据。

    def get_context_data(self, **kwargs):
        check_for_zipcode = self.request.user.profile.location
        context = super().get_context_data(**kwargs)
        context['zipcodes'] = {'check_for_zipcode' : check_for_zipcode}
        return context
    

    现在您可以像以前一样访问 html 中的变量了

    【讨论】:

      猜你喜欢
      • 2013-08-16
      • 2015-05-23
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 2021-07-17
      • 2015-02-02
      相关资源
      最近更新 更多