python - How can I subclass a modelform (extend with extra fields from the model)? -


i have model , form:

class mymodel(models.model):     field_foo = models.charfield(_("foo"), max_length=50)     field_bar = models.integerfield(_("bar"))  class myformone(forms.modelform):     class meta:         model=mymodel         fields = ('field_foo', )         widgets = {'field_foo': forms.textinput(attrs={'size': 10, 'maxlength': 50}),} 

i have form myformtwo subclass form including field field_bar. point not have repeat widget declaration field_foo in second form (dry principle), , not have repeat list of fields myformone (in reality there more 1 field in simple example above).

how should define myformtwo?

you shouldn't have explicitly declare entire widget, modify attrs different. or if have custom widgets in real code, either

  1. create custom model field class uses widget default, if it's general condition, in form class works "automagically".
  2. if it's form specific (not model specific), case i'd declare form field explicitly on form class, not in meta , inheritance applies in straightforward way.

but default widgets (with custom attrs) i'd try following

class mymodel(models.model):     field_foo = models.charfield(_("foo"), max_length=50)     field_bar = models.integerfield(_("bar"))  class myformone(forms.modelform):     class meta:         model=mymodel         fields = ('field_foo', )      def __init__(*args, **kwargs):         super(myformone, self).__init__(*args, **kwargs)          self.fields['field_foo'].widget.attrs['size'] = 10         # max_length should set automatically model         # textinput default widget charfield  class myformtwo(myformone):     class meta:         model=mymodel         fields = myformone.meta.fields + ('field_foo2',)      def __init__(*args, **kwargs):         super(myformtwo, self).__init__(*args, **kwargs)          self.fields['field_foo2'].widget.attrs['size'] = 10 

Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

c# - SharpSVN - How to get the previous revision? -

php cli reading files and how to fix it? -