需求
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
>
|