0

I'm using floppyforms with modelforms, and the only documentation on them is to specify widgets via the class Meta. However, I want my textarea widget placeholder to depend on a form variable, and Meta doesn't have access to class variables. Any tips on achieving this in the framework as is?

Right now I've got this in 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'}),
        }

I realize I could use standard (non modelforms) forms and declare the fields/widgets using variables, but was wondering if there's a way to do it without sacrificing model validation.

sybaritic
  • 392
  • 6
  • 15

1 Answers1

1

You can define those attributes via the field's widget

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
    });
kviktor
  • 1,076
  • 1
  • 12
  • 26
  • This works. A better way of defining widgets than Meta, it seems to me. Not sure why floppyforms docs don't use it. Thanks! – sybaritic Nov 19 '14 at 03:53
  • If you use Meta, you don't have to override the __init__ method, but you can't use dynamic values. – kviktor Nov 19 '14 at 09:02