[英]Convert CharField to ChoiceField Dynamically in Django Forms?
In Django, How can I convert a field from CharField
to ChoiceField
dynamically? 在Django中,如何将字段从CharField
动态转换为ChoiceField
? Could you please help me to fix the below traceback error? 您能帮我解决以下回溯错误吗?
For example, 例如,
This is my below model: 这是我的以下模型:
class Clients(models.Model):
#senegal
city_order = models.CharField(max_length=40, null=True, verbose_name='City Orderform')
email = models.EmailField(verbose_name='Email Address')
duration = models.CharField(max_length=100, blank=True, null=True, verbose_name="Duration")
Note: fields_for_model is used to fetch the fields. 注意: fields_for_model用于获取字段。
ModelForm: from django.forms.models import fields_for_model ModelForm:从django.forms.models导入fields_for_model
class Argentina(forms.ModelForm):
class Meta:
model = Clients
fields = ['duration', 'email']
def __init__(self, *args, **kwargs):
city = kwargs.pop('city_order')
super(Argentina, self).__init__(*args, **kwargs)
if city.lower() == 'senegal':
#Changing the fields dynamically based on the city
_fields = ['duration']
self.fields = fields_for_model(Clients, _fields)
#here the type of the field need to be changed to choicefield from charfield which is default by model definition.
self.fields['duration'] = forms.ChoiceField(choices = (('Sample', 'Testing')), label="Duration")
This field type will be changed based on the explicit attribute city
.The fields are created dynamically and field type also has to be changed as defined in the ModelForm called Argentinal
above. 该字段类型将基于显式属性city
进行更改。字段是动态创建的,并且字段类型也必须按照上面称为Argentinal
的ModelForm中的定义进行更改。
Traceback: I get ValueError
in Django Template. 追溯:我在Django模板中得到ValueError
。 Too many values to unpack
. Too many values to unpack
。
Django Version: 1.6.6
Python Version: 2.7.8
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'bootstrapform',
'orders')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
112. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/nava/ws/vbservices/vbservices/orders/views.py" in ordersubmission
88. print "form",form
File "/usr/lib/python2.7/dist-packages/django/utils/encoding.py" in <lambda>
60. klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
File "/usr/lib/python2.7/dist-packages/django/forms/forms.py" in __str__
103. return self.as_table()
File "/usr/lib/python2.7/dist-packages/django/forms/forms.py" in as_table
223. errors_on_separate_row = False)
File "/usr/lib/python2.7/dist-packages/django/forms/forms.py" in _html_output
186. 'field': six.text_type(bf),
File "/usr/lib/python2.7/dist-packages/django/forms/forms.py" in __str__
425. return self.as_widget()
File "/usr/lib/python2.7/dist-packages/django/forms/forms.py" in as_widget
475. return widget.render(name, self.value(), attrs=attrs)
File "/usr/lib/python2.7/dist-packages/django/forms/widgets.py" in render
504. options = self.render_options(choices, [value])
File "/usr/lib/python2.7/dist-packages/django/forms/widgets.py" in render_options
528. for option_value, option_label in chain(self.choices, choices):
Exception Type: ValueError at /travel/senegal/
Exception Value: too many values to unpack
This has nothing to do with dynamic fields, nor about converting from a char field. 这与动态字段无关,也与从char字段转换无关。 The issue is solely that choices needs to be a 2- tuple - that is, a sequence of pairs. 问题仅在于选择必须是2元组-即,成对的序列。
choices = (('sample', Sample'), ('testing 'Testing'))
self.fields['duration'] = forms.ChoiceField(choices=choices, label="Duration")
Also note that your call to fields_for_model seems pointless: that has already been done by the superclass init method. 还要注意,对fields_for_model的调用似乎毫无意义:超类init方法已经完成了此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.