我正在显示一个已保存到数据库的发布表单。我为用户提供了查看数据库中的值和编辑这些值的选项。但是,它不适用于dropdown。我试着写了一些东西,但它没有显示正确的值。
请帮帮忙:((
以下是代码片段:
<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)发布于 2021-04-29 17:57:08
好吧,这只是因为如果你已经有了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>https://stackoverflow.com/questions/67311966
复制相似问题