【问题标题】:Django. Pass variable from view to template姜戈。将变量从视图传递到模板
【发布时间】:2016-11-06 20:54:10
【问题描述】:

我想将变量 appuser 传递给模板,但我不明白该怎么做。 我尝试使用kwargs.update,但它仍然不起作用。

我有一个看法:

class CausesView(AjaxFormView):
    appuser = None
    causes = []
    cause_allocation_set = None

    def prepare_request(self, request, *args, **kwargs):
        self.causes = Cause.objects.filter(is_main_cause = True)
        self.appuser = AppUser.get_login_user(request)
        self.cause_allocation_set = set([r.cause_id for r in self.appuser.current_cause_save_point.cause_allocations_list])

    def prepare_context(self, request, context, initial):
        initial.update(
            causes = self.cause_allocation_set,
            appuser = self.appuser,
            )

    def prepare_form(self, request, form):
        form._set_choices("causes", [(r.id, r.title) for r in self.causes])

    def custom_context_data(self, request, **kwargs):
        kwargs.update(
            special_test = "dsf"
        )
        return kwargs

    def process_form(self, request, form):
        data = form.cleaned_data

        try:
            with transaction.atomic():
                if self.cause_allocation_set != set(data.get('causes')):
                    self.appuser.save_causes(data.get('causes'))
        except Exception as e:
            message = "There was an error with saving the data: " + str(e.args)
            return AjaxErrorResponse({'title':"Error", 'message':message})
        return AjaxSuccessResponse('Causes Saved')

我有一个表格:

class CauseForm(AjaxForm):
    causes = forms.TypedMultipleChoiceField(label="Select Causes", choices = (), required = False, coerce = int,
                    widget = forms.CheckboxSelectMultiple())

    def clean(self):
        cleaned_data = super(CauseForm, self).clean()
        causes = cleaned_data.get('causes')

        validation_errors = []
        if not causes is None and not len(causes):
            validation_errors.append(forms.ValidationError("At least one Cause is required"))

        if len(validation_errors):
            raise forms.ValidationError(validation_errors)
        return cleaned_data

如何在模板中获取变量 appuser? 例如:

{{ appuser.name }}

没用。

【问题讨论】:

    标签: django django-forms django-templates django-views


    【解决方案1】:

    阅读How to use get_context_data in djangohttps://docs.djangoproject.com/en/1.9/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_context_data

    这里是你如何做到这一点的例子

    class CausesView(AjaxFormView):
        ...
        def get_context_data(self, **kwargs):
            context_data = super(CausesView, self).get_context_data(**kwargs)
            context_data['appuser'] = self.appuser
            return context_data
    

    【讨论】:

    • 谢谢,但在这里不起作用,我认为是因为项目是自定义的。但是我找到了解决方案,只需在prepare_context中添加context.update({ 'appuser': self.appuser, })即可。很奇怪。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2017-12-13
    相关资源
    最近更新 更多