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

后端 未结 26 1271
-上瘾入骨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:19

    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:

    {{ form.instance.sku }} {{ form }}

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

提交回复
热议问题