以django形式获取外键值

时间:2014-08-11 11:51:37

标签: python django

我创建了一个forms.py,model.py和views.py,如下所示。

Model.py中的一个表

 class Billing_Detail(models.Model):
       bill_choices = [('Permanent','Permanent'),('Temporary','Temporary')]
       emp_name = models.ForeignKey(Employee)
       emp_proj = models.ForeignKey(Project)
       bill_type = models.CharField(max_length = 10,choices=bill_choices,verbose_name='Bill type')
       start_date = models.DateField(blank=True,verbose_name='Billing Start Date',null=True)
       end_date = models.DateField(blank=True,verbose_name='Billing End Date',null=True)

forms.py

  class AddBillingForm(forms.Form):
            emp_list = Employee.objects.filter()
            proj_list = Project.objects.filter()
            bill_type = ['Permanent','Temporary']
            Employee = forms.ModelChoiceField(queryset=Employee.objects.all())
            Project =  forms.ModelChoiceField(queryset=Project.objects.all())
            #Sub_Project = forms.ChoiceField(choices=get_my_choices())
            Sub_Project =  forms.ModelChoiceField(queryset=Sub_Project.objects.all())
            Billing_Type = forms.ChoiceField(choices=zip(bill_type,bill_type))
            Billing_Start_Date = forms.DateField
            Billing_End_Date = forms.DateField

views.py

  def addbilling(request):
        if request.method == 'GET':
            form = AddBillingForm()
        else:
            #A POST request
            form = AddBillingForm(request.POST)
            if form.is_valid():
                print "inside"
                post = form.save(commit=False)
                print post
                employee = form.cleaned_data['Employee']
                print employee
                return HttpResponse('thanks')

        return render(request, 'addbilling.html', {'form': form,})

以上一切都很好。除非我提交表格。它验证它然后给我form.cleaned_data ['Employee']中的值。但它给了我这个名字。但我需要该名称的ID,以便我可以正确插入数据库

0 个答案:

没有答案