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

后端 未结 26 962
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:09

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 recor

相关标签:
26条回答
  • 2020-11-22 04:37

    I've just created the simplest possible widget for a readonly field - I don't really see why forms don't have this already:

    class ReadOnlyWidget(widgets.Widget):
        """Some of these values are read only - just a bit of text..."""
        def render(self, _, value, attrs=None):
            return value
    

    In the form:

    my_read_only = CharField(widget=ReadOnlyWidget())
    

    Very simple - and gets me just output. Handy in a formset with a bunch of read only values. Of course - you could also be a bit more clever and give it a div with the attrs so you can append classes to it.

    0 讨论(0)
  • 2020-11-22 04:38

    For django 1.9+
    You can use Fields disabled argument to make field disable. e.g. In following code snippet from forms.py file , I have made employee_code field disabled

    class EmployeeForm(forms.ModelForm):
        employee_code = forms.CharField(disabled=True)
        class Meta:
            model = Employee
            fields = ('employee_code', 'designation', 'salary')
    

    Reference https://docs.djangoproject.com/en/dev/ref/forms/fields/#disabled

    0 讨论(0)
提交回复
热议问题