Monday, December 9, 2013

Django - Create a form with read-only field

To Create a read-only field for a form in Django:


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


Example: 

class AddStudentAccountForm(forms.Form):
         first_name = forms.CharField(max_length=100)
         last_name = forms.CharField(max_length=100)
         unique_id = forms.CharField(max_length=10)
         description = forms.CharField(max_length=255, initial='Students <Grad Year>', widget=forms.TextInput(attrs={'readonly':'readonly'}))
         department = forms.CharField(max_length=255, initial='SSIS Students', widget=forms.TextInput(attrs={'readonly':'readonly'}))
         grad_year = forms.ChoiceField(choices=YEARS)