2016-07-05 85 views
2

我想將變量appuser傳遞給模板,但我不明白該怎麼做。 我試圖使用kwargs.update,但它仍然無法正常工作。Django。將變量從視圖傳遞到模板

我有一個觀點:

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在temlpate? 例如:

{{ appuser.name }} 

不起作用。

回答

2

閱讀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 
+0

謝謝,但它並沒有在這裏工作,我認爲這是因爲該項目是自定義的。但是我找到了一個解決方案,只需將'context.update'('appuser':self.appuser, }')添加到prepare_context。真奇怪。 –

相關問題