将ForeignKey添加到ModelForm

时间:2015-06-14 13:33:52

标签: django django-forms

我尝试创建此表单,包含2个外键,client和company_name

我不断收到客户端字段所需的错误。此代码是否不将客户端添加到模型表中?

    class BillableForm(forms.ModelForm):
        date = forms.DateField(label='date', input_formats=['%d %b %Y'], initial=datetime.date.today)
        class Meta:
            model = Billable
            fields = ('b_type', 'number', 'date', 'VAT_percentage')

        def __init__(self, *args, **kwargs):
            client = kwargs.pop('client','')
            company = kwargs.pop('company','')
            super(BillableForm, self).__init__(*args, **kwargs)
            self.fields['client'] = forms.ModelChoiceField(client)



def index(request):
    if request.method == "POST":

        obj = request.POST

        company, created = Company.objects.get_or_create(
            name=obj['my_company_name'], 
            info=obj['company_info'], 
            banking_details=obj['extra_1'], 
            extra=obj['extra_2']
        )
        client, created = Client.objects.get_or_create(
            name=obj['client_name'], 
            email=None, 
            address=obj['client_address'], 
            number=obj['client_number']
        )


        form = BillableForm(request.POST, client=client, company=company)

        if form.is_valid():
            form.save()
        else:
            print form.errors

我不确定我做错了它仍然表示它需要表单中的client和company_name?

0 个答案:

没有答案