In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?

Viewed 377288

In a Django form, how do I make a field read-only (or disabled)?

When the form is being used to create a new entry, all fields should be enabled - but when the record is in update mode some fields need to be read-only.

For example, when creating a new Item model, all fields must be editable, but while updating the record, is there a way to disable the sku field so that it is visible, but cannot be edited?

class Item(models.Model):
    sku = models.CharField(max_length=50)
    description = models.CharField(max_length=200)
    added_by = models.ForeignKey(User)


class ItemForm(ModelForm):
    class Meta:
        model = Item
        exclude = ('added_by')

def new_item_view(request):
    if request.method == 'POST':
        form = ItemForm(request.POST)
        # Validate and save
    else:
            form = ItemForm()
    # Render the view

Can class ItemForm be reused? What changes would be required in the ItemForm or Item model class? Would I need to write another class, "ItemUpdateForm", for updating the item?

def update_item_view(request):
    if request.method == 'POST':
        form = ItemUpdateForm(request.POST)
        # Validate and save
    else:
        form = ItemUpdateForm()
30 Answers

As pointed out in this answer, Django 1.9 added the Field.disabled attribute:

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.

With Django 1.8 and earlier, to disable entry on the widget and prevent malicious POST hacks you must scrub the input in addition to setting the readonly attribute on the form field:

class ItemForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            self.fields['sku'].widget.attrs['readonly'] = True

    def clean_sku(self):
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            return instance.sku
        else:
            return self.cleaned_data['sku']

Or, replace if instance and instance.pk with another condition indicating you're editing. You could also set the attribute disabled on the input field, instead of readonly.

The clean_sku function will ensure that the readonly value won't be overridden by a POST.

Otherwise, there is no built-in Django form field which will render a value while rejecting bound input data. If this is what you desire, you should instead create a separate ModelForm that excludes the uneditable field(s), and just print them inside your template.

Setting readonly on a widget only makes the input in the browser read-only. Adding a clean_sku which returns instance.sku ensures the field value will not change on form level.

def clean_sku(self):
    if self.instance: 
        return self.instance.sku
    else: 
        return self.fields['sku']

This way you can use model's (unmodified save) and avoid getting the field required error.

For Django 1.2+, you can override the field like so:

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

Yet again, I am going to offer one more solution :) I was using Humphrey's code, so this is based off of that.

However, I ran into issues with the field being a ModelChoiceField. Everything would work on the first request. However, if the formset tried to add a new item and failed validation, something was going wrong with the "existing" forms where the SELECTED option was being reset to the default ---------.

Anyway, I couldn't figure out how to fix that. So instead, (and I think this is actually cleaner in the form), I made the fields HiddenInputField(). This just means you have to do a little more work in the template.

So the fix for me was to simplify the Form:

class ItemForm(ModelForm):

    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.id:
            self.fields['sku'].widget=HiddenInput()

And then in the template, you'll need to do some manual looping of the formset.

So, in this case you would do something like this in the template:

<div>
    {{ form.instance.sku }} <!-- This prints the value -->
    {{ form }} <!-- Prints form normally, and makes the hidden input -->
</div>

This worked a little better for me and with less form manipulation.

You can elegantly add readonly in the widget:

class SurveyModaForm(forms.ModelForm):
    class Meta:
        model  = Survey
        fields = ['question_no']
        widgets = {
        'question_no':forms.NumberInput(attrs={'class':'form-control','readonly':True}),
        }

Two more (similar) approaches with one generalized example:

1) first approach - removing field in save() method, e.g. (not tested ;) ):

def save(self, *args, **kwargs):
    for fname in self.readonly_fields:
        if fname in self.cleaned_data:
            del self.cleaned_data[fname]
    return super(<form-name>, self).save(*args,**kwargs)

2) second approach - reset field to initial value in clean method:

def clean_<fieldname>(self):
    return self.initial[<fieldname>] # or getattr(self.instance, fieldname)

Based on second approach I generalized it like this:

from functools                 import partial

class <Form-name>(...):

    def __init__(self, ...):
        ...
        super(<Form-name>, self).__init__(*args, **kwargs)
        ...
        for i, (fname, field) in enumerate(self.fields.iteritems()):
            if fname in self.readonly_fields:
                field.widget.attrs['readonly'] = "readonly"
                field.required = False
                # set clean method to reset value back
                clean_method_name = "clean_%s" % fname
                assert clean_method_name not in dir(self)
                setattr(self, clean_method_name, partial(self._clean_for_readonly_field, fname=fname))

    def _clean_for_readonly_field(self, fname):
        """ will reset value to initial - nothing will be changed 
            needs to be added dynamically - partial, see init_fields
        """
        return self.initial[fname] # or getattr(self.instance, fieldname)

Today I encountered the exact same problem for a similar use case. However, I had to deal with a class-based views. Class-based views allow inheriting attributes and methods thus making it easier to reuse code in a neat manner.

I will answer your question by discussing the code needed for creating a profile page for users. On this page, they can update their personal information. However, I wanted to show an email field without allowing the user to change the information.

Yes, I could have just left out the email field but my OCD would not allow it.

In the example below I used a form class in combination with the disabled = True method. This code is tested on Django==2.2.7.


# form class in forms.py

# Alter import User if you have created your own User class with Django default as abstract class.
from .models import User 
# from django.contrib.auth.models import User

# Same goes for these forms.
from django.contrib.auth.forms import UserCreationForm, UserChangeForm


class ProfileChangeForm(UserChangeForm):

    class Meta(UserCreationForm)
        model = User
        fields = ['first_name', 'last_name', 'email',]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['email'].disabled = True

As one can see, the needed user fields are specified. These are the fields that must be shown on the profile page. If other fields need to be added one has to specify them in the User class and add the attribute name to the fields list of the Meta class of this form.

After getting the required metadata the __init__ method is called initializing the form. However, within this method, the email field parameter 'disabled' is set to True. By doing so the behavior of the field in the front-end is altered resulting in a read-only field that one cannot edit even if one changes the HTML code. Reference Field.disabled

For completion, in the example below one can see the class-based views needed to use the form.


# view class in views.py

from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import TemplateView, UpdateView
from django.utils.translation import gettext_lazy as _


class ProfileView(LoginRequiredMixin, TemplateView):
    template_name = 'app_name/profile.html'
    model = User


   def get_context_data(self, **kwargs):
      context = super().get_context_data(**kwargs)
      context.update({'user': self.request.user, })
      return context


class UserUpdateView(LoginRequiredMixin, SuccesMessageMixin, UpdateView):
    template_name = 'app_name/update_profile.html'
    model = User
    form_class = ProfileChangeForm
    success_message = _("Successfully updated your personal information")


    def get_success_url(self):
        # Please note, one has to specify a get_absolute_url() in the User class
        # In my case I return:  reverse("app_name:profile")
        return self.request.user.get_absolute_url()


    def get_object(self, **kwargs):
        return self.request.user


    def form_valid(self, form):
        messages.add_message(self.request, messages.INFO, _("Successfully updated your profile"))
        return super().form_valid(form)


The ProfileView class only shows an HTML page with some information about the user. Furthermore, it holds a button that if pressed leads to an HTML page configured by the UserUpdateView, namely 'app_name/update_profile.html'. As one can see, the UserUpdateView holds two extra attributes, namely 'form_class' and 'success_message'.

The view knows that every field on the page must be filled with data from the User model. However, by introducing the 'form_class' attribute the view does not get the default layout of the User fields. Instead, it is redirected to retrieve the fields through the form class. This has a huge advantage in the sense of flexibility.

By using form classes it is possible to show different fields with different restrictions for different users. If one sets the restrictions within the model itself every user would get the same treatment.

The template itself is not that spectacular but can be seen below.


# HTML template in 'templates/app_name/update_profile.html' 

{% extends "base.html" %}
{% load static %}
{% load crispy_form_tags %}


{% block content %}


<h1>
    Update your personal information
<h1/>
<div>
    <form class="form-horizontal" method="post" action="{% url 'app_name:update' %}">
        {% csrf_token %} 
        {{ form|crispy }}
        <div class="btn-group">
            <button type="submit" class="btn btn-primary">
                Update
            </button>
        </div>
</div>


{% endblock %}

As can be seen, the form tag holds an action tag that holds the view URL routing. After pressing the Update button the UserUpdateView gets activated and it validates if all conditions are met. If so, the form_valid method is triggered and adds a success message. After successfully updating the data the user is returned to the specified URL in the get_success_url method.

Below one can find the code allowing the URL routing for the views.

# URL routing for views in urls.py

from django.urls import path
from . import views

app_name = 'app_name'

urlpatterns = [
    path('profile/', view=views.ProfileView.as_view(), name='profile'),
    path('update/', view=views.UserUpdateView.as_view(), name='update'),
    ]

There you have it. A fully worked out implementation of class-based views using form so one can alter an email field to be read-only and disabled.

My apologies for the extremely detailed example. There might be more efficient ways to design the class-based views, but this should work. Of course, I might have been wrong about some things said. I'm still learning as well. If anyone has any comments or improvements let me know!

You can do it just like this:

  1. Check if the request is update or save a new object.
  2. If request is update then disable field sku.
  3. If request is to add a new object then you must render the form with out disabling the field sku.

Here is an example of how to do like this.

class Item(models.Model):
    sku = models.CharField(max_length=50)
    description = models.CharField(max_length=200)
    added_by = models.ForeignKey(User)


class ItemForm(ModelForm):
    def disable_sku_field(self):
        elf.fields['sku'].widget.attrs['readonly'] = True

    class Meta:
        model = Item
        exclude = ('added_by')

def new_item_view(request):
    if request.method == 'POST':
        form = ItemForm(request.POST)
        # Just create an object or instance of the form.
        # Validate and save
    else:
            form = ItemForm()
    # Render the view

def update_item_view(request):
    if request.method == 'POST':
        form = ItemForm(request.POST)
        # Just create an object or instance of the form.
        # Validate and save
    else:
        form = ItemForm()
        form.disable_sku_field() # call the method that will disable field.

    # Render the view with the form that will have the `sku` field disabled on it.

If you are working with Django ver < 1.9 (the 1.9 has added Field.disabled attribute) you could try to add following decorator to your form __init__ method:

def bound_data_readonly(_, initial):
    return initial


def to_python_readonly(field):
    native_to_python = field.to_python

    def to_python_filed(_):
        return native_to_python(field.initial)

    return to_python_filed


def disable_read_only_fields(init_method):

    def init_wrapper(*args, **kwargs):
        self = args[0]
        init_method(*args, **kwargs)
        for field in self.fields.values():
            if field.widget.attrs.get('readonly', None):
                field.widget.attrs['disabled'] = True
                setattr(field, 'bound_data', bound_data_readonly)
                setattr(field, 'to_python', to_python_readonly(field))

    return init_wrapper


class YourForm(forms.ModelForm):

    @disable_read_only_fields
    def __init__(self, *args, **kwargs):
        ...

The main idea is that if field is readonly you don't need any other value except initial.

P.S: Don't forget to set yuor_form_field.widget.attrs['readonly'] = True

Start from disable fields mixin:

class ModelAllDisabledFormMixin(forms.ModelForm):
    def __init__(self, *args, **kwargs):
    '''
    This mixin to ModelForm disables all fields. Useful to have detail view based on model
    '''
    super().__init__(*args, **kwargs)
    form_fields = self.fields
    for key in form_fields.keys():
        form_fields[key].disabled = True

then:

class MyModelAllDisabledForm(ModelAllDisabledFormMixin, forms.ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'

prepare view:

class MyModelDetailView(LoginRequiredMixin, UpdateView):
    model = MyModel
    template_name = 'my_model_detail.html'
    form_class = MyModelAllDisabledForm

place this in my_model_detail.html template:

  <div class="form">
     <form method="POST" enctype="multipart/form-data">
         {% csrf_token %}
         {{ form | crispy }}
     </form>
  </div>

You will obtain same form as in update view but with all fields disabled.

Based on the answer from @paeduardo (which is overkill), you can disable a field in the form class initializer:

class RecordForm(ModelForm):

     def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            var = self.fields['the_field']
            var.disabled = True
Related