根据实例值创建窗体小部件 [英] Creating form widgets based on instance values

查看:81
本文介绍了根据实例值创建窗体小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型:

  VARIABLE_CHOICES =(
('bool','On / )
('date','Date'),
('float','Number'),
('text','Text'),


class LetterVariable(models.Model):
name = models.CharField(max_length = 20)
type = models.CharField(max_length = 5,choices = VARIABLE_CHOICES)
data = models.CharField(max_length = 100)

我想创建一个表单,当我通过它是一个来自数据库的 LetterVariable 的实例,它将为数据创建具有腐蚀性的小部件,在请输入



任何想法我该怎么做?

解决方案
$(






$ ).__ init __(* args,** kwargs)

如果不是self.instance:
引发异常(你忘了实例!);

如果self.instance.type =='something':
self.fields ['data']。widget = forms.SomeWidget()


I have the following model:

VARIABLE_CHOICES = (
    ('bool', 'On/Off'),
    ('date', 'Date'),
    ('float', 'Number'),
    ('text', 'Text'),
)

class LetterVariable(models.Model):
    name = models.CharField(max_length=20)
    type = models.CharField(max_length=5, choices=VARIABLE_CHOICES)
    data = models.CharField(max_length=100)

I want to create a form that when I pass it an instance of LetterVariable from the db it will create the corrosponding widget for data bassed upon type.

Any ideas how I might do this?

解决方案

class LetterVariableForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(LetterVariableForm, self).__init__(*args, **kwargs)

        if not self.instance:
           raise Exception('You forgot the instance!');

        if self.instance.type == 'something':
            self.fields['data'].widget = forms.SomeWidget()

这篇关于根据实例值创建窗体小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆