前言
select下拉框选项经常会需要从数据库动态拿数据,每次刷新页面能拿到最新的数据。
Teacher 模型
Teacher 表
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
class Teacher(models.Model):
"""老师表"""
name = models.CharField(max_length=30)
age = models.IntegerField(blank=True, null=True)
tel = models.CharField(max_length=30)
表里面新增一些数据
form与views
form 表单设计下拉框,下拉框的值读取Teacher表的id和name字段
from django import forms
from .models import Teacher
from django.forms import widgets
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
class SelectDemo(forms.Form):
teacher = forms.CharField(
label="老师",
initial=[1, ],
widget=widgets.Select())
# 保证每次访问重新获取最新数据
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["teacher"].widget.choices = Teacher.objects.values_list("id", "name")
数据库读取的数据返回list of tuple格式,如
[
("1", "悠悠老师"),
("2", "张三老师"),
("3", "李四老师"),
("4", "王五老师"),
]
views.py视图打开页面
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
class SelectDemoView(View):
def get(self, request):
form_obj = SelectDemo()
return render(request, "select.html", locals())
模板
模板中读取select下拉框字段
<form action="" method="POST" id="detail-form" >
{% csrf_token %}
{% for field in form_obj %}
<p>
{{ field.label_tag }}
{{ field }}
{{ field.errors }}
</p>
{% endfor %}
<p>
<input type="submit" value="提交" >
</p>
</form>
select下拉框显示效果