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

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

    To make this work for a ForeignKey field, a few changes need to be made. Firstly, the SELECT HTML tag does not have the readonly attribute. We need to use disabled="disabled" instead. However, then the browser doesn't send any form data back for that field. So we need to set that field to not be required so that the field validates correctly. We then need to reset the value back to what it used to be so it's not set to blank.

    So for foreign keys you will need to do something like:

    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'].required = False
                self.fields['sku'].widget.attrs['disabled'] = 'disabled'
    
        def clean_sku(self):
            # As shown in the above answer.
            instance = getattr(self, 'instance', None)
            if instance:
                return instance.sku
            else:
                return self.cleaned_data.get('sku', None)
    

    This way the browser won't let the user change the field, and will always POST as it it was left blank. We then override the clean method to set the field's value to be what was originally in the instance.

提交回复
热议问题