如何在django选择表单中传递值?

时间:2016-04-19 06:29:52

标签: python django django-models django-forms django-views

我正在创建发票申请。 我有一个模型应收账款

class Receivables(models.Model):
    user=models.ForeignKey(settings.AUTH_USER_MODEL)
    receivable_name=models.CharField(max_length=250)
    receivable_address=models.CharField(max_length=250,blank=True)
    receivable_email=models.CharField(max_length=250,blank=True)
    receivable_telephone=models.CharField(max_length=250,blank=True)
    receivable_VAT=models.CharField(max_length=250,blank=True)
    receivable_Service_Tax=models.CharField(max_length=250,blank=True)
    receivable_PAN=models.CharField(max_length=250,blank=True)

    def __str__(self):
        return self.user.receivable_name 

将模型服务发送为

class serviceinvoice(models.Model):
    user=models.ForeignKey(User,related_name='invoice')    
    invoice_number=models.PositiveIntegerField()
    invoice_date = models.DateField(auto_now_add=True)
    invoice_receivable=models.ForeignKey(Receivables)
    total_amount=models.DecimalField(decimal_places=2,max_digits=20)
    total_amountwithtax=models.DecimalField(decimal_places=2,max_digits=20)

    def __str__(self):
        return invoice_number

serviceinvoice模型的form.py

class createinvoiceform(forms.ModelForm):
    class Meta:
        model=serviceinvoice
        exclude=('user',)

此表单的views.py为

@login_required
def createinvoice(request):
    if request.method == 'POST':
        inv_form=createinvoiceform(data=request.POST)
        if inv_form.is_valid():
            new_form=inv_form.save(commit=False)
            new_form.user=request.user
            new_form.save()
            return HttpResponse('Invoice created')
    else:
        inv_form=createinvoiceform()
    return render(request,'account/createinvoice.html',{'inv_form':inv_form})

现在我面临的问题是:

  1. 呈现的模板不显示Receivalbe名称,而是显示self.user.receivalbe_name
  2. 如何显示仅与登录用户相关的receivalbe_name?

1 个答案:

答案 0 :(得分:0)

通过在views.py中添加以下内容解决了第二个问题:

inv_form=createinvoiceform()
        inv_form.fields["invoice_receivable"].queryset=Receivables.objects.filter(user=request.user)