Django - ModelForm Dynamic field update

后端 未结 4 847
情书的邮戳
情书的邮戳 2021-01-06 11:50

I\'m trying to update certain fields a ModelForm, these fields are not fixed. (I have only tutor that is autopopulated by the view)

Model:



        
4条回答
  •  耶瑟儿~
    2021-01-06 12:38

    Put your form fields as nullable and with "clean" methods you can add logic to fields ex:

    class SessionForm(forms.ModelForm):
        def clean_end_date(self):
            cd = self.cleaned_data
            if (cd["start_date"] and cd["end_date"]) and cd["end_date"] < cd["start_date"]:
                raise forms.ValidationError("WTF?!")
            if not (cd["start_date"] or cd["end_date"]):
                raise forms.ValidationError("need one date")
            return cd['end_date']
    

    If you want to change value, use a different value to the return statement.

    This is what you may need for validation.

    If you want, you may copy GET dictionary in your view and update values before instanciate your form

    def my_view(request):
        r_data = request.GET.copy()
        r_data.merge(request.POST)
    
        data = dict([(key, my_function(key, value)) for key, value in r_data.iteritems() if key in MyForm.fields])
        form = MyForm(data=data)
        [...]
    

    hopes it help.

提交回复
热议问题