gpt4 book ai didi

python - 在 Django 表单中动态将 CharField 转换为 ChoiceField?

转载 作者:太空宇宙 更新时间:2023-11-03 17:50:15 24 4
gpt4 key购买 nike

在 Django 中,如何动态地将字段从 CharField 转换为 ChoiceField?您能帮我修复以下回溯错误吗?

例如,

这是我的以下模型:

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")

注:fields_for_model用于获取字段。

模型表单: 从 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")

此字段类型将根据显式属性city进行更改。字段是动态创建的,并且字段类型也必须按照称为Argentinal的模型表单中的定义进行更改如上所述。

回溯: 我在 Django 模板中收到 ValueError值太多,无法解压

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

最佳答案

这与动态字段无关,也与从 char 字段转换无关。问题只是选择需要是一个 2 元组 - 即一系列对。

choices = (('sample', Sample'), ('testing 'Testing'))
self.fields['duration'] = forms.ChoiceField(choices=choices, label="Duration")

另请注意,您对 fields_for_model 的调用似乎毫无意义:这已经由父类(super class) init 方法完成了。

关于python - 在 Django 表单中动态将 CharField 转换为 ChoiceField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29196334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com