disabled field is not passed through - workaround needed

后端 未结 7 523
夕颜
夕颜 2020-12-10 03:29

I have a form with which I want to update a MyModel object. On the model there is a unique_together constraint, fieldA together with fieldB. In the form in the clean method

7条回答
  •  悲&欢浪女
    2020-12-10 03:40

    I had a little fun looking into how forms works and came up with multiple solutions, just for the heck of it.

    Since you are disabling the widget and not the field, as far as the form is concerned it's always receiving nothing for fieldA and that will always fail validation.

    Trying something in the clean() method won't help for invalid forms because clean() data is for processing.

    It looks like the way forms pull data for HTML display is field.data, which is a call to field.widget.value_from_datadict(POST, FILES, field_name) so it will always be looking at your POST data.

    So I think you have a few options. Hack request.POST, hack the internal form POST data, or hack value_from_datadict.


    Hacking request.POST: straight forward, makes sense.

        myModelobject = get_object_or_404(MyModel.objects, pk=mymodel_id)
    
            if request.method == 'POST':
                POST = request.POST.copy()
                POST['fieldA'] = myModelobject.fieldA
                model_form = MyModelUpdateForm(POST, instance=myModelobject )
    
                if model_form .is_valid():
                    # ...
    

    Hacking internal dictionary:

    def __init__(self, *args, **kwargs):
        super(MyModelUpdateForm, self).__init__(*args, **kwargs)
        self.data.update({ 'fieldA': self.instance.fieldA })
    

    Hacking value_from_datadict: kinda ridiculous, but illustrates what you can learn from digging into the source

    def __init__(self, *args, **kwargs):
        super(MyModelUpdateForm, self).__init__(*args, **kwargs)
        self.fields['fieldA'].widget.value_from_datadict = lambda *args: self.instance.first_name
    

    Learned some cool things here : ) Hope it helps.

提交回复
热议问题