Django Form, make readonly field

Question:

I’m trying to create a Form with Django and i’m aiming to have a readonly field, without success. The field should contain a code that is calculated in the view but i need to show it to the user.

This is the Model:

class Customer(models.Model):
    name = models.CharField(max_length = 250)
    note = models.CharField(max_length=500,blank=True,null=True)
    code = models.IntegerField(null=True,blank=True,unique=True)

This is the Form:

class NewCustomerForm(forms.ModelForm):
    class Meta:
        model = Customer
        fields = ['name', 'code', 'note']

That should be pretty easy but i’m facing a lot of problems. What I’ve already tryed:

  1. Field.disabled = True (the documentation don’t explaine where should i put this attribute so maybe i’m getting something wrong)
  2. self.fields['code'].widget.attrs['readonly'] = True in __init __
  3. self.fields['code'].widget.attrs['disabled'] = True in __init __

In all of three method the field remain editable by the user

Asked By: Tiziano Pedrazzoli

||

Answers:

If the code field value is not needed in the html output, I would suggest to exclude the field from the form and calculate the value in the view of the form is valid.
You can assign the calculated value to the model instance in your view before saving.

class YourView(views.CreateView):
    def form_valid(self, form):
        form.instance.code = your_calculated_value
        return super().form_valid(form)
Answered By: JanMalte

The HTML input will always be editable by the user, even if you set readonly or disabled to true, the user can just remove both of those flags and type in a value!

However, as long as the field renders as readonly or disabled, and it’s apparent to the user that the field is fixed, and your python code sets a fixed value that ignores user input, you should be fine.

Answered By: 0sVoid