Django Forms: Foreign Key in Hidden Field

后端 未结 5 471
我在风中等你
我在风中等你 2020-12-18 21:06

My form:

class PlanForm(forms.ModelForm):    
    owner = forms.ModelChoiceField(label=\"\",
                                  queryset=Profile.objects.all()         


        
5条回答
  •  庸人自扰
    2020-12-18 22:07

    When you assign a Profile object to the form, Django stringifies it and uses the output as the value in the form. What you would expect though, is for Django to use the ID of the object instead.

    Luckily, the workaround is simple: Just give the form primary key values of the Profile objects instead:

    form = PlanForm(initial={'profile': profile.pk})
    

    On the other end, when you're working with bound forms, however, they work much more sensibly:

    form = PlanForm(request.POST)
    if form.is_valid():
        print form.cleaned_data['profile']  # the appropriate Profile object
    

提交回复
热议问题