Django creating a form field that's read only using widgets


Question

My form field looks something like the following:

class FooForm(ModelForm):
    somefield = models.CharField(
        widget=forms.TextInput(attrs={'readonly':'readonly'})
    )

    class Meta:
        model = Foo

Geting an error like the following with the code above: init() got an unexpected keyword argument 'widget'

I thought this is a legitimate use of a form widget?

1
15
3/1/2010 8:03:57 PM

Accepted Answer

You should use a form field and not a model field:

somefield = models.CharField(
    widget=forms.TextInput(attrs={'readonly':'readonly'})
)

replaced with

somefield = forms.CharField(
    widget=forms.TextInput(attrs={'readonly':'readonly'})
)

Should fix it.

40
12/1/2009 6:27:30 PM

Note that the readonly attribute does not keep Django from processing any value sent by the client. If it is important to you that the value doesn't change, no matter how creative your users are with FireBug, you need to use a more involved method, e.g. a ReadOnlyField/ReadOnlyWidget like demonstrated in a blog entry by Alex Gaynor.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon