首页 文章

在Meta,Django Floppyforms中访问表单变量

提问于
浏览
0

我正在使用带有模型的软盘,其唯一的文档是通过Meta类指定小部件 . 但是,我希望我的textarea小部件占位符依赖于表单变量,而Meta不能访问类变量 . 有关在框架中实现此目的的任何提示吗?

现在我在forms.py中得到了这个:

class ChapterForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.placeholder = "Chapter " + (kwargs.pop('number'))
        super(ChapterForm,self).__init__(*args, **kwargs)
    class Meta:
        model = Chapter
        fields = ("name", "text", ...)
        widgets = {
            "name": PlaceholderInput(attrs={'placeholder':self.placeholder, 'class':'headline'}),
        }

我意识到我可以使用标准(非模型)形式并使用变量声明字段/小部件,但是想知道是否有办法在不牺牲模型验证的情况下完成它 .

1 回答

  • 1

    您可以通过字段的小部件定义这些属性

    from django.forms.widgets import TextInput
    
    def __init__(self, *args, **kwargs):
        self.placeholder = "Chapter %s" % kwargs.pop('number')
        super(ChapterForm,self).__init__(*args, **kwargs)
    
        self.fields['name'].widget = TextInput(attrs={
            'class': "headline",
            'placeholder': self.placeholder
        });
    

相关问题