Django:在ModelForm中选择父模型的实例

时间:2016-10-31 02:57:32

标签: python django forms

我想在create.html选择父模型产品的实例,然后将数据发送到views.py。但是,我无法弄清楚如何做到这一点。我已经在create.html中选择了产品实例,但我不确定如何将数据发送到views.py并保存。

{% for product in products %}
  <option value="{{ product.id }}">{{ product.name}}</option>
  <div class="error">{{ form.product.id.errors }}</div>
{% endfor %}

create.html上

~~~  
<div>  
  <select>
    {% for product in products %}
      <option value="{{ product.id }}">{{ product.name}}</option>
      <div class="error">{{ form.product.id.errors }}</div>
    {% endfor %}
  </select>
</div>
<div>
  <label for="invoice_no">INOVICE NO:</label>
    {{ form.invoice_no }}
  <div class="error">{{ form.invoice_no.errors }}</div>
</div>
~~~

views.py

from django.shortcuts import redirect, render
from django.http import HttpResponse
from .models import Invoice
from account.models import User
from .forms import InvoiceForm

def index(request):
    d = {
        'invoices' : Invoice.objects.all(),
    }
    return render(request, 'invoice/index.html', d)

def create(request):
    user = request.user
    if request.method == 'POST':
        form = InvoiceForm(request.POST)
        if form.is_valid():
            invoice = form.save(commit=False)
            invoice.user = user
            invoice.save()
            return redirect('/invoice')
        else:
            return redirect('/')
    else:
        products = user.products.all()
        form = InvoiceForm()
        return render(request, 'invoice/create.html', {'form': form, 'products':products})

models.py

from django.db import models

from account.models import User
from product.models import Product

class Invoice(models.Model):
    user = models.ForeignKey(User, verbose_name='User', related_name='invoices', default=1, null=True)
    product = models.ForeignKey(Product, verbose_name='Product', related_name='invoices', default=1, null=True)
    invoice_no = models.IntegerField('Invoice No')

forms.py

from django import forms
from .models import Invoice
from product.models import Product

class InvoiceForm(forms.ModelForm):
    class Meta:
        model = Invoice
        fields = (
            'product',
            'invoice_no',
        )

        widgets = {
            'product': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Product'}),
            'invoice_no': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Invoice No'}),

        }

2 个答案:

答案 0 :(得分:1)

您可以通过提交html表单将数据发送到服务器。请参阅教程第4步中的表单示例 - https://docs.djangoproject.com/en/1.10/intro/tutorial04/ 有关html表单的一般说明,请参阅http://www.w3schools.com/html/html_forms.asp

答案 1 :(得分:0)

我刚刚解决了。通过添加$gateway->setPrivateKey('-----BEGIN RSA PRIVATE KEY-----MIICXAI... ,我实现了它。谢谢您的合作!

name="product"