python - How can I disable a model field in a django form -
i have model this:
class mymodel(models.model): regular = 1 premium = 2 status_choices = ((regular, "regular"), (premium, "premium")) name = models.charfield(max_length=30) status = models.integerfield(choices = status_choices, default = regular) class myform(forms.modelform): class meta: model = models.mymodel
in view initialize 1 field , try make non-editable:
myform = myform(initial = {'status': requested_status}) myform.fields['status'].editable = false
but user can still change field.
what's real way accomplish i'm after?
use html readonly attribute:
http://www.w3schools.com/tags/att_input_readonly.asp
or disabled
http://www.w3.org/tr/html401/interact/forms.html#adef-disabled
you can inject arbitrary html key value pairs via widget attrs property:
myform.fields['status'].widget.attrs['readonly'] = true # text input myform.fields['status'].widget.attrs['disabled'] = true # radio / checkbox
this post has nice trick ensuring form can't accept new values: in django form, how make field readonly (or disabled) cannot edited?
override clean method field regardless of post input (somebody can fake post, edit raw html, etc.) value started with.
def clean_status(self): return self.instance.status
Comments
Post a Comment