我正在显示一个已保存到数据库中的过帐表单。我为用户提供了在数据库中查看值的选项,并为他提供了编辑值的选项。但是,它不适用于下拉列表。我试过写一些东西,但它没有显示正确的值。
请帮忙:
以下是代码片段:
<div class="form-group col-md-6">
<label for="industry_type">Industry Type</label>
<select class="form-control" id="industry_type" name="industry_type" selected="
{{ internship.industry_type }}">
{% for ind_type in industry_types %}
<option value="{{ ind_type }}" {% if '{{ ind_type }}' == '{{
internship.industry_type }}' %}selected="selected" {% endif %}>
{{ind_type}}</option>
{% endfor %}
</select>
</div>
views.py
def edit_internship(request, pid):
internship = Internship.objects.get(id=pid)
skills = InternshipSkill.objects.filter(internship=internship)
emp_steps = InternshipEmpStep.objects.filter(internship=internship)
.order_by('emp_step_no')
industry_types = IndustryType.objects.all()
context = {
'industry_types': industry_types,
'internship': internship,
'skills': skills,
'emp_steps': emp_steps,
}
return render(request, 'edit_internship.html', context)
好吧,这只是因为如果你已经有了花括号,就不需要在django的模板中重新添加它们:
<div class="form-group col-md-6">
<label for="industry_type">Industry Type</label>
<select class="form-control" id="industry_type" name="industry_type" selected="{{ internship.industry_type.pk }}">
{% for ind_type in industry_types %}
<option value="{{ ind_type.pk }}" {% if ind_type.pk == internship.industry_type.pk %}selected="selected" {% endif %}>
{{ ind_type }}
</option>
{% endfor %}
</select>
</div>
另外,在声明值时,不要忘记ind_type
的.pk
参数。
为了将来的参考,我真的建议你在创建这些表单时使用Django的表单,这会让你更容易点赞:
views.py
class EditInternship(UpdateView):
model = Internship
template_name = 'edit_internship.html'
form_class = EditInternshipForm
def get_context_data(**kwargs):
ctx = super().get_context_data(**kwargs)
ctx.update(
skills=InternshipSkill.objects.filter(internship=internship),
emp_steps=InternshipEmpStep.objects.filter(internship=internship).order_by('emp_step_no')
)
# You'll also have `form` already in the context
return ctx
edit_internship = EditInternship.as_view()
forms.py
class EditInternshipForm(forms.ModelForm):
class Meta:
model = Internship
fields = 'industry_type', 'other_fields_on_the_model_you_want_to_edit'
edit_internship.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.industry_type }}
{{ form.other_fields_you_want_to_edit }}
<input type="submit" name="submit_button" value="Save" class="btn btn-primary btn-sm" id="submit_button">
</form>