在Django Forms中动态地将CharField转换为ChoiceField?

时间:2015-03-22 15:42:49

标签: python django django-models

在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用于获取字段。

的ModelForm:     来自django.forms.models import 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的ModelForm中的定义进行更改。

回溯:我在Django模板中获得ValueErrorToo 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

1 个答案:

答案 0 :(得分:1)

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

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

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