我試圖創建一個使用模型關係生成表單集的動態表單。Django動態表單,帶有HTML數組的表單集
下面是應用程序的簡要概述。我有一個客戶表(加入到django admin用戶表),產品表,訂單表和一些連接表。 customer_product表包含可以編輯的預先構建的訂單表單。我使用一些連接表來創建新的order_instances,這些新的order_instances可以從歷史數據的訂單表中引用。
`客戶與用戶表一一對應的關係
customer table
--------------
id
product table
-------------
id | product_id
`客戶有屬於許多產品
customer_product (pre-built order templates)
----------------
id | customer_id | product_id
「客戶有屬於許多產品。客戶有很多訂單
customer_product_order (customer initiated order)
----------------------
id | customer_id | product_id | order_id | quantity
order (main order table. each record contains meta data for that order)
-------
id | invoice_number | delivery_date
我不知道如何在這種情況下使用的表單集,可以讓被建立動態表單和保存到customer_product_order表和順序表。目前我有表單輸出,但它是第二次檢查customer_product表,而不是讓forms.py oncstruct它。也無法在forms.py頁面中構建html數組。
models.py
from django.conf import settings
from django.db import models
from datetime import datetime
import pprint
class Customer(models.Model):
customer = models.ForeignKey(settings.AUTH_USER_MODEL, limit_choices_to={'groups__name': "customers"})
customer_product = models.ManyToManyField('Product', through='CustomerProduct')
company_name = models.CharField(max_length=255)
address1 = models.CharField(max_length=255)
address2 = models.CharField(max_length=255)
city = models.CharField(max_length=255)
state = models.CharField(max_length=255)
zip_code = models.CharField(max_length=255)
created_date = models.DateTimeField('date created')
def __unicode__(self):
return self.company_name
class CustomerProduct(models.Model):
customer = models.ForeignKey('Customer')
product = models.ForeignKey('Product')
def __unicode__(self):
return self.customer.company_name
class Product(models.Model):
item = models.CharField(max_length=255)
description = models.CharField(max_length=255)
def __unicode__(self):
return self.description
class Order(models.Model):
customer_product_order = models.ManyToManyField('CustomerProduct', through='CustomerProductOrder')
purchase_order_number = models.CharField(max_length=10)
person_placing_order = models.CharField(max_length=255)
class CustomerProductOrder(models.Model):
order = models.ForeignKey('Order')
customer_product = models.ForeignKey('CustomerProduct')
quantity = models.IntegerField(default=0)
instructions = models.CharField(max_length=2000)
order_correct = models.BooleanField()
def __unicode__(self):
return self.customer_product.customer.company_name
class Meta:
verbose_name = "Customer Order"
forms.py
from django import forms
from .models import CustomerProduct
class OrderForm(forms.Form):
def __init__(self, *args, **kwargs):
products = CustomerProduct.objects.filter(customer_id=1)
super(OrderForm, self).__init__(*args, **kwargs)
counter = 1
for q in products:
self.fields['product[quantity][' + str(q.id) + ']' + str(counter)] = forms.CharField(required=False)
self.fields['product[item][' + str(q.id) + ']' + str(counter)] = forms.CharField(required=False)
self.fields['product[description][' + str(q.id) + ']' + str(counter)] = forms.CharField(required=False)
counter += 1
purchase_order_number = forms.CharField(required=True)
person_placing_order = forms.CharField(required=True)
delivery_date_request = forms.DateField(required=True,widget=forms.DateInput(attrs={'class':'datepicker'}))
instructions = forms.CharField(required=False,widget=forms.Textarea(attrs={'rows': 5, 'cols': 100, 'class': 'form-control'}))
confirm_order = forms.BooleanField(required=True)
views.py
from django import forms
from .models import CustomerProduct
class OrderForm(forms.Form):
def __init__(self, *args, **kwargs):
products = CustomerProduct.objects.filter(customer_id=1)
super(OrderForm, self).__init__(*args, **kwargs)
counter = 1
for q in products:
self.fields['product[quantity][' + str(q.id) + ']' + str(counter)] = forms.CharField(required=False)
self.fields['product[item][' + str(q.id) + ']' + str(counter)] = forms.CharField(required=False)
self.fields['product[description][' + str(q.id) + ']' + str(counter)] = forms.CharField(required=False)
counter += 1
purchase_order_number = forms.CharField(required=True)
person_placing_order = forms.CharField(required=True)
delivery_date_request = forms.DateField(required=True,widget=forms.DateInput(attrs={'class':'datepicker'}))
instructions = forms.CharField(required=False,widget=forms.Textarea(attrs={'rows': 5, 'cols': 100, 'class': 'form-control'}))
confirm_order = forms.BooleanField(required=True)
模板
{% extends "base.html" %}
{% block orderform %}
{% if form.errors %}
<p style="color: red;">
Please correct the error{{ form.errors|pluralize }} below.
</p>
{% endif %}
<form action="/onlineordering/" method="POST">
<form class="form-inline">
{% csrf_token %}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div class="row">
<div class="col-md-5"><label for="exampleInputName2">Date</label></div>
<div class="col-md-7">{{ datenow }}</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-5"><label for="exampleInputName2">Customer ID:</label></div>
<div class="col-md-7">{{ username }}</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-5"><label for="exampleInputName2">Address</label></div>
<div class="col-md-7">
1 Main Street<br />
Town<br />
State<br />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-5"><label for="exampleInputName2">Purchase Order Number</label></div>
<div class="col-md-7">{{ form.purchase_order_number }}</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-5"><label for="exampleInputEmail2">Person Placing Order</label></div>
<div class="col-md-7">{{ form.person_placing_order }}</div>
</div>
</div>
<div class="form-group">
<div class="form-group">
<div class="row">
<div class="col-md-5"><label for="exampleInputEmail2">Requested Delivery Date</label></div>
<div class="col-md-7">{{ form.delivery_date_request }}</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<p class="text-right">
</p>
</div>
</div>
<table class="table table-bordered online-ordering-table">
<tr>
<th width="10%">Quantity</th>
<th width="20%">Item</th>
<th width="70%">Description</th>
</tr>
{% for product in products %}
<tr>
<td><input name="product_quantity" /></td>
<td>{{ product.product.item }}</td>
<td>{{ product.product.description }}</td>
</tr>
{% endfor %}
</table>
<div class="form-group">
<label for="exampleInputEmail2">Special Instructions/Comments</label>
{{ form.instructions }}
</div>
<div class="form-group">
<div class="checkbox">
<label>
{{ form.confirm_order }} I concede the order above is correct and authorize Company to fulfill this order
</label>
</div>
</div>
<input class="btn" type="submit" value="Submit">
</form>
</form>
{% endblock %}
UPDATE
關於模型的評論。我儘可能詳細地描述了上面的關係。該應用程序的設計和要求如下。每個客戶擁有一個用戶。客戶訂單表由管理員預先建立並存儲在customer_product表中。客戶hasand belongstomany產品和客戶hasmanyorders。當客戶下訂單時,會添加新的訂單記錄,並填入customer_products_order連接表以及每個產品的數量。
customer_product表由管理員預先填充。 customer_product_order(加入)和訂單表由客戶填充。
我正在使用以下連接從訂單模型中獲取客戶信息。我找不到任何其他方式遞歸加入訂單模型中的客戶表。我可能是錯的。即使這個問題超出了這個問題,我真的很感激我的代碼的任何意見!
models.ManyToManyField('CustomerProduct', through='CustomerProductOrder')
在進入關於動態formset生成的細節之前,我對你的模型類有點好奇。你能否提供關於每個「模型」背後意圖的更多細節? 特別是,您的設計使得您似乎希望能夠** **不同的客戶** ** **訂單,這是故意的嗎? –
不,這不是故意的。我的目的不是讓一個訂單有不同的客戶。公司=客戶。訂單下達時,「人員下訂單」字段是當天下單的員工。 – madphp
在你的設計中,'Order'有**許多''CustomerProduct''。由於每個CustomerProduct都有一個Customer,所以一個Order可以有多個不同的Customer。另外,由於ManyToMany關係是雙向的,同一個'CustomerProduct'可以是不同'Order'的一部分。所有這些選擇都違背了直觀的設計(例如,違反了任何給定'Order'都有一個'Customer'的事實)。我想你應該給出關於你的每個'Model'類和你的設計決定背後的意圖的更多細節,以便得到一些答案。 –