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 2 years, 10 months ago
  2. DisplayModelForm by koenb 3 years, 8 months ago
  3. Dynamically change admin widgets at runtime by davisd 1 year, 9 months ago
  4. Selectively change fields, widgets or labels in forms created from models by danjak 4 years, 11 months ago
  5. Add attrs automaticlly through ModelForm field max_length by lettoo 3 weeks ago

Comments

guettli (on September 17, 2008):

Related: Snippet 755

#

(Forgotten your password?)