我正在使用基于类的视图,并且想在我的UpdateView的ward
方法中获取给定字段get_context_data
的当前值。我尝试使用get
方法,但无法正常工作。这是我的方法:
def get_context_data(self, **kwargs):
context = super(ApplicationUpdateView, self).get_context_data(**kwargs)
context['money_per_ward'] = int(getattr(Allocation.objects.first(), 'amount_allocated') / 30)
context['ward'] = self.request.POST.get('ward') # <-- This prints "None"
return context
我的完整UpdateView:
class ApplicationUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = Application
form_class = ApplicationForm
success_message = "Details Updated Successfully"
extra_context = {
'title' : 'Edit Application Details'
}
def get_context_data(self, **kwargs):
context = super(ApplicationUpdateView, self).get_context_data(**kwargs)
context['money_per_ward'] = int(getattr(Allocation.objects.first(), 'amount_allocated') / 30)
context['ward'] = self.request.POST.get('ward')
return context
还有我的urls.py:
path('apply/', default_views.ApplicationCreateView.as_view(), name='apply'),
path('applications/<int:pk>/update/', default_views.ApplicationUpdateView.as_view(), name='edit_application'),
和我的模板:
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
{% if title == 'Apply' %}
<legend class="border-bottom mb-4">Apply For Bursary</legend>
{% elif title == 'Edit Application Details' %}
<legend class="border-bottom mb-4">Edit details for {{application.full_name}}
</legend>
{% else %}
<legend class="border-bottom mb-4"></legend>
{% endif %}
<div class="row">
<div class="col-md-6">
<h5 class="border-bottom mb-4">Personal Details</h5>
<div class="border-bottom mb-4">
{{ form.full_name|as_crispy_field }}
{{ form.gender|as_crispy_field }}
{{ form.parent_name|as_crispy_field }}
{{ form.contact|as_crispy_field }}
</div>
<h5 class="border-bottom mb-4">School Details</h5>
{{ form.category|as_crispy_field }}
{{ form.school_name|as_crispy_field }}
{{ form.adm_number|as_crispy_field }}
{{ form.year|as_crispy_field }}
</div>
<div class="col-md-6">
<h5 class="border-bottom mb-4">Location Details</h5>
{{ form.subcounty|as_crispy_field }}
{{ form.ward|as_crispy_field }}
{{ form.sublocation|as_crispy_field }}
<small class="text-muted">Money: {{money_per_ward}} {{ward}}</small>
{{ form.is_qualified|as_crispy_field}}
</div>
</div>
</fieldset>
<div class="form-group">
<button class="btn btn-block btn-outline-info" name="submit" type="submit">
{% if title == 'Apply' %}
Submit Application
{% else %}
Update Details
{% endif %}
</button>
</div>
</form>
有没有一种方法可以访问此字段{{form.ward|as_crispy_field}}
的当前值?
答案 0 :(得分:0)
我的坏。我只需要使用self.get_object()
方法。
这是可行的解决方案:
def get_context_data(self, **kwargs):
context = super(ApplicationUpdateView, self).get_context_data(**kwargs)
context['money_per_ward'] = int(getattr(Allocation.objects.first(), 'amount_allocated') / 30)
context['ward'] = self.get_object().ward # <-- Now this works perfectly
return context