Django--form生成select标签
需求
Django--form表单中的select生成方法,如果select中的选项不固定,需要怎么操作。
速查
1、固定select选项
forms
1
2
3
|
class
表单类名称(forms.Form):
host_type
=
forms.IntegerField(
widget
=
forms.Select(choices
=
列表或元组)
|
2、动态select选项
forms
1
2
3
4
5
6
7
|
admin
=
forms.IntegerField(
widget
=
forms.Select()
)
def
__init__(
self
,
*
args,
*
*
kwargs):
#执行父类的构造方法
super
(ImportForm,
self
).__init__(
*
args,
*
*
kwargs)
self
.fields[
'admin'
].widget.choices
=
models.SimpleModel.objects.
all
().values_list(
'id'
,
'username'
)
#每次都会去数据库中获取这个列表
|
知识点
-
select的form格式是元组括元组,提交的是value(数字),字段类型是forms.IntegerField,插件widget=forms.Select(),属性choices=元组列表
-
面向对象中静态字段只要加载到内存就不会改变了,私有字段每次提交都刷新,原理是实例化对象的时候把静态字段进行了deepcopy到对象里,修改的时候就私有字段修改,静态字段不变。
详细
1、生成最基本的select标签
templates/home/index.html
1
2
3
4
5
6
7
8
9
|
<
body
>
<
h1
>录入数据</
h1
>
<
form
action
=
"/index/"
>
<
p
>{{ obj.host_type }}</
p
>
<
p
>{{ obj.hostname }}</
p
>
</
form
>
<
h1
>数据列表</
h1
>
...
</
body
>
|
app01/urls.py
1
2
3
4
|
from
app01.views
import
account,home
urlpatterns
=
[
url(r
'^index/$'
,home.index ),
]
|
app01/views/home.py
1
2
3
4
|
from
app01.forms
import
home as HomeForm
def
index(request):
obj
=
HomeForm.ImportForm(request.POST)
return
render(request,
'home/index.html'
,{
'obj'
:obj})
|
app01/forms/home.py
1
2
3
4
5
6
7
8
9
10
|
from
django
import
forms
class
ImportForm(forms.Form):
HOST_TYPE_LIST
=
(
(
1
,
'物理机'
),
(
2
,
'虚拟机'
)
)
host_type
=
forms.IntegerField(
widget
=
forms.Select(choices
=
HOST_TYPE_LIST)
)
hostname
=
forms.CharField()
|
browser
2、可变的select标签
app01/models.py
1
2
3
|
class
SimpleModel(models.Model):
username
=
models.CharField(max_length
=
64
)
password
=
models.CharField(max_length
=
64
)
|
初始化数据库
Django-Path > python manage.py makemigrations
Django-Path > python manage.py migrate
数据库app01_simplemodel表,随便造两条数据
app01/forms/home.py中添加:
1
2
3
4
5
6
7
8
9
|
from app01
import
models
admin = forms.IntegerField(
widget=forms.Select()
)
def __init__(self,*args,**kwargs): #执行父类的构造方法
super
(ImportForm,self).__init__(*args,**kwargs)
self.fields[
'admin'
].widget.choices = models.SimpleModel.objects.all().values_list(
'id'
,
'username'
)
#每次都会去数据库中获取这个列表
|
index.html加入admin选项
1
|
<
p
>{{ obj.admin }}</
p
>
|
browser
当往数据库表中添加一个管理员时,看select标签选项