change a widget attribute in ModelForm without define the field

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from django import forms
from django.contrib.auth.models import User 

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

        # change a widget attribute:
        self.fields['user_permissions'].widget.attrs["size"] = 5
         
    class Meta:
        model = User 

More like this

  1. Add model form field meta data in a DRY way by jedie 5 years, 1 month ago
  2. Reorder fields directly in the ModelForm by HM 5 years, 11 months ago
  3. Dynamically change admin widgets at runtime by davisd 4 years ago
  4. Selectively change fields, widgets or labels in forms created from models by danjak 7 years, 1 month ago
  5. ModelForm Class saving m2m by ckarrie2 2 years, 6 months ago

Comments

(Forgotten your password?)