SANGEETH SUBRAMONIAM
SANGEETH SUBRAMONIAM

Reputation: 1086

Making form fields - read only or disabled in DJANGO updateView

I have a model which I will update using an updateView generic class based function. How can I make specific fields as read only ?

example :

Models.py:

class Employee(models.Model):
    emp_no = models.IntegerField( primary_key=True)
    birth_date = models.DateField()
    first_name = models.CharField(max_length=14)
    last_name = models.CharField(max_length=16)
    gender = models.CharField(max_length=1)
    hire_date = models.DateField()

    class Meta:
        verbose_name = ('employee')
        verbose_name_plural = ('employees')
        # db_table = 'employees'

    def __str__(self):
        return "{} {}".format(self.first_name, self.last_name)

views.py :

class EmployeeUpdate(UpdateView):
    
    
    model = Employee
    fields = '__all__'

How can I make the first_name readonly inside a UpdateView ? Note: I want to have the model(charfield) the same, But it should be read only inide an UpdateView.

Upvotes: 1

Views: 1050

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21787

When one wants to customize their forms the easiest way is to make a form class. A generic view is not really meant to provide all features a form class does, even though it makes life a little easy by generating the form for you by itself.

You want to be using a ModelForm [Django docs] and set disabled=True [Django docs] on your field:

from django import forms

class EmployeeUpdateForm(forms.ModelForm):
    first_name = forms.CharField(max_length=14, disabled=True)
    
    class Meta:
        model = Employee
        fields = '__all__'

Note: The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be editable by users. Even if a user tampers with the field’s value submitted to the server, it will be ignored in favor of the value from the form’s initial data.

Now in your view you simply want to set the form_class attribute:

class EmployeeUpdate(UpdateView):
    model = Employee
    form_class = EmployeeUpdateForm

Upvotes: 2

Related Questions