Django Forms: Foreign Key in Hidden Field

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

My form:

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


        
5条回答
  •  佛祖请我去吃肉
    2020-12-18 21:52

    I suspect that the __unicode__ method for the Profile model instance, or the repr thereof is set to return a value other than self.id. For example, I just set this up:

    # models.py
    class Profile(models.Model):
        name = models.CharField('profile name', max_length=10)
    
        def __unicode__(self):
            return u'%d' % self.id
    
    class Plan(models.Model):
        name = models.CharField('plan name', max_length=10)
        profile = models.ForeignKey(Profile, related_name='profiles')
    
        def __unicode__(self):
            return self.name
    
    
    # forms.py
    class PlanForm(forms.ModelForm):
        profile = forms.ModelChoiceField(queryset=Profile.objects.all(),
                widget=forms.HiddenInput())
    
        class Meta:
            model = Plan
    
    # views.py
    def add_plan(request):
    
        if request.method == 'POST':
            return HttpResponse(request.POST['profile'])
    
    
        profile = Profile.objects.all()[0]
        form = PlanForm(initial={'profile':profile})
        return render_to_response('add_plan.html',
                {
                    'form':form,
                },
                context_instance=RequestContext(request))
    

    With that, I see PlanForm.profile rendered thus in the template:

    
    

提交回复
热议问题