Make a foreign key field in a django form read-only, and still enable the form to be submitted

ε祈祈猫儿з 提交于 2019-12-04 13:52:15

I don't know the Django or Python syntax, however, an input field of type="hidden" might be what you're looking for. If you wanted to still display the value using a disabled field, you could do that too, and rely on the hidden field for the actual value.

Maybe I can try the hidden field...I knew this was a possibility, but I wanted to be sure there was no other way

I've had this problem and I used JavaScript to solve

I came across this question after many other solutions didn't seem to work. Here's example code of how I got it work successfully using the "hidden" suggestion, in case it's helpful to anyone else.

class EditExifForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(EditExifForm, self).__init__(*args, **kwargs)
        self.fields['image'].widget.attrs['hidden'] = True    # This is the solution
        # Setting as 'readonly' didn't make a difference
        # Setting as 'disabled' made the form not update the database

    class Meta:
        model = exif
        ...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!