Ich möchte Variable Appuser zu Vorlage übergeben und ich verstehe nicht, wie es geht. Ich habe versucht, kwargs.update
zu verwenden, aber es funktioniert immer noch nicht.Django. Übergeben Sie die Variable von der Ansicht zur Vorlage
Ich habe einen Blick:
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')
Und ich habe eine Form:
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
Wie kann ich Variable appuser in temlpate bekommen? Zum Beispiel:
{{ appuser.name }}
funktioniert nicht.
Danke, aber es funktioniert hier nicht, ich denke, es ist, weil das Projekt Brauch ist. Aber ich finde eine Lösung, fügen Sie einfach 'context.update ({ 'appuser': self.appuser, }}' zu prepare_context hinzu. Es ist komisch. –