簡體   English   中英

在Django表單中將CharField動態轉換為ChoiceField嗎?

[英]Convert CharField to ChoiceField Dynamically in Django Forms?

在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導入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模板中得到ValueError 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

這與動態字段無關,也與從char字段轉換無關。 問題僅在於選擇必須是2元組-即,成對的序列。

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

還要注意,對fields_for_model的調用似乎毫無意義:超類init方法已經完成了此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM