首先:我無法找出這個問題的正確標題。如何從給定的選擇初始化django-form數據類型字段?
總之,問題是:
我必須填寫在模板的形式和這種形式的字段是用戶依賴。例如,你經過integer
(整數是不是一個數據類型)作爲參數的方法,它應該這樣返回:
fileds = forms.IntegerField()
如果傳遞bool
那麼它應該是這樣的:
fields = forms.BooleanField()
所以我可以使用它們來創建我的表單。我試着用這段代碼,但它返回到字符串的形式。
Some.py文件:
choices = (('bool','BooleanField()'),
('integer','IntegerField()'))
def choose_field():
option = 'bool' # Here it is hardcoded but in my app it comes from database.
for x in choices:
if x[0]==option:
type = x[1]
a = 'forms'
field = [a,type]
field = ".".join(field)
return field
當我打印領域它打印'forms.BooleanField()'
。我也使用這個返回值,但它沒有工作。艾米解決這個問題?
爲什麼不'型=字典(選擇)[選項]'? (你可能會在後面的某個地方運行不必要的'eval',而不是'getattr'。) – dhill