gpt4 book ai didi

python - Django : Maintaining option selected in HTML template

转载 作者:太空宇宙 更新时间:2023-11-04 02:33:14 25 4
gpt4 key购买 nike

当我在 html 模板中使用 django if 函数来设置对所选选项标签的更改时,但它一直选择 --SELECT-- 选项

 <form  method="post">

<select name="name">
<option >--SELECT--</option>
{% for job in all_pekerjaan%}
<option value="{{job.id}}"
{% if job.id == current_name %}selected="selected"{% endif %}>
{{job.name}}
</option>
{% endfor %}
</select>
{% csrf_token %}

<input type="submit" class="btn btn-success" value="submit" >
</form>

这是我的views.py

from django.http import HttpResponse
from .models import daftartabel, Pekerjaan
from .forms import form1, form2
from django.template import loader
from django.shortcuts import render

def index(request):

if request.method == 'POST':
#print(request.POST['name'])
current_name=request.POST['name']
all_datas = daftartabel.objects.filter(pekerjaan_id=request.POST['name'])
else:
all_datas = daftartabel.objects.all()
all_pekerjaan = Pekerjaan.objects.all()
template = loader.get_template('tabel/index.html')
#print(all_datas)
#print(all_pekerjaan)
context = {
'all_datas' : all_datas,
'all_pekerjaan' : all_pekerjaan,
'current_name' : request.POST['name'],
}
#print (context)
print(type(context['current_name']))

return HttpResponse(template.render(context, request))

我的forms.py 类

class form2(forms.Form):
name = forms.CharField(max_length=100)

有人知道如何解决这个问题吗?

最佳答案

问题已解决,将“current_name”更改为整数会有所帮助。

if request.method == 'POST':
context = {
'all_datas' : all_datas,
'all_pekerjaan' : all_pekerjaan,
'current_name' : int(request.POST['name']),
}
else:
context = {
'all_datas' : all_datas,
'all_pekerjaan' : all_pekerjaan,
}

关于python - Django : Maintaining option selected in HTML template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48575518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com