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

后端 未结 26 1538
-上瘾入骨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.

提交回复
热议问题