How to set initial values for a ModelForm when instance is also given

后端 未结 3 1397
庸人自扰
庸人自扰 2021-01-02 06:54

It seems like if a ModelForm is given an instance, it ignores any values you provide for initial and instead sets it to the value of the instance -- even if tha

3条回答
  •  天命终不由人
    2021-01-02 07:23

    Sounds to me that you may be looking for a bound form. Not entirely sure, I'm trying to unpick a similar issue:

    Django forms can be instantiated with two arguments which control this kind of thing. As I understand it:

    form = MyForm(initial={...}, data={...}, ...)
    

    initial will set the possible values for the fields—like setting a queryset—data will set the actual (or selected) values of a form and create a bound form. Maybe that is what you want. Another, tangental, point you might find interesting is to consider a factory method rather than a constructor, I think the syntax is more natural:

    class MyForm(forms.ModelForm):
    
        ...
    
        @staticmethod
        def makeBoundForm(user):
            myObjSet = MyObject.objects.filter(some_attr__user=user)
            if len(myObjSet) is not 0:
                data = {'myObject': myObjSet[0]}
            else:
                raise ValueError()
            initial = {'myObject': myObjSet}
            return MyForm(initial=initial, data=data)
    

提交回复
热议问题