在通过表格更新我的数据时,我该如何在选择选项中首先显示已经选择的老师
models.py
class TeacherSalary(models.Model):
name = models.ForeignKey(Teacher,on_delete=CASCADE)
total_num_of_students = models.IntegerField(default=0)
fee_per_student = models.IntegerField(default=0)
total_fee = models.IntegerField(default=0)
percent_for_teacher = models.FloatField(default=0.0)
salary = models.IntegerField(default=0)
views.py
def editteachersalary(request,id):
if not request.user.is_superuser:
messages.info(request, 'You have to logged in first as a admin')
return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
teachers = Teacher.objects.all()
teacher = TeacherSalary.objects.get(id=id)
# for teacher1 in teachers:
# if teacher1.id == teacher.id and teacher1.name == teacher.name:
# selected_option = True
return render(request, 'students/edit_teacher_salary.html', {'teacher': teacher,'teachers':teachers})
编辑模板
<div class="form-group">
<h5>Teacher <span class="text-danger">*</span></h5>
<div class="controls">
<select name="name" id="select" required class="form-control">
{% for teacher1 in teachers %}
<option value="{{teacher1.id}}" {% if teacher1.id == teacher.id and teacher1.name == teacher.name %} selected="selected"{% endif %}>{{teacher1.name}}
</option>
{% endfor %}
</select>
</div>
</div>
答案 0 :(得分:2)
{% for teacher1 in teachers %}
<option value="{{ teacher1.id }}"
{% if teacher1.id== teacher.name_id %}
selected {% endif %}>
{{ teacher1.name }}
</option>
{% endfor %}
答案 1 :(得分:1)
您正在比较GetPropValue()
和Teacher
实例。您应该将TeacherSalary
的每个项目与teachers
而不是teacher.name
进行比较。
teacher
或者您可以将{% for teacher1 in teachers %}
<option value="{{ teacher1.id }}" {% if teacher1 == teacher.name %} selected {% endif %}>
{{ teacher1.name }}
</option>
{% endfor %}
更改为teacher = TeacherSalary.objects.get(id=id)
。