python - 渲染表单字段随机时间

标签 python django forms

我对表单中的字段渲染有疑问。我有这段代码:

class RTForm(forms.ModelForm):

    type_options = {
        'error': {
            'label': _('Error'),
        },
        'warning': {
            'label': _('Warning'),
        },
        'off': {
            'label': _('Disable'),
        }
    }

    choice_type = forms.ChoiceField(
        choices=[(k, v['label']) for k, v in type_options.items()],
        required=True, widget=forms.RadioSelect(
            attrs={
                class="choices"
            }
        )
    )

    class Meta:
        model = RT

    def __init__(self, *args, **kwargs):
        self.rt = kwargs.pop('instance', None)

        errors = create_error_list(rt.type)
        warnings = create_warning_list(rt.type)

        super(RTV, self).__init__(*args, **kwargs)

我想做的是在我的模板上拥有与初始化列表中返回的错误/警告数量一样多的 choice_type 字段(每次不同的数字)。那可能吗?我想不出可能的解决方案。

最佳答案

在您使用 type ( http://docs.python.org/2/library/functions.html#type ) 创建的动态类的帮助下,您的要求将成为可能

我不确定我是否正确理解了您问题的业务需求,但是我会在 View 中执行类似的操作以创建自定义表单:

choice_type = forms.ChoiceField( # this is your class
   choices=[(k, v['label']) for k, v in type_options.items()],
   required=True, widget=forms.RadioSelect(attrs={
           class="choices"
       })
)

# let's say that I want my custom form to have two choice fields:
formfields = {}
formfields['choice_field1']= choice_type 
formfields['choice_field2']= choice_type 

# Now I can create my custom class
form_class = type('CustomForm', (django.forms.Form,), formfields )

# Finally I will create an instance of my custom class
form = form_class()

# Ok ! form can be used in my view as any normal django form !!

关于python - 渲染表单字段随机时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19446013/

相关文章:

python - Django : how to define a unique slug for an abstract model and its children?

django - Django rest ModelViewSet过滤对象

javascript - 按条件提交函数中的表单

java - Spring 分段上传

python - 使用字典替换字符串

python - 无法将数组转换为 float python

python - 如何克隆列表以使其在分配后不会意外更改?

javascript - 如何在不重新加载页面的情况下更新 Django 页面?

python - 如何使 python 对象 json 序列化?

javascript - jquery 防止提交时重新加载表单