gpt4 book ai didi

Django 。将变量从 View 传递到模板

转载 作者:行者123 更新时间:2023-12-02 03:21:25 26 4
gpt4 key购买 nike

我想将变量 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

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

{{ appuser.name }}

不起作用。

最佳答案

阅读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

关于 Django 。将变量从 View 传递到模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38196322/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com