我的模板中有两个表单,我想要做的是将新添加的模型添加到另一个模型的属性中。模型分别是客户和订单。 (一旦我添加了客户,我想向其客户添加订单,新添加的订单)
以下是我的客户观点
def add_customer(request):
form = CustomerForm(request.POST or None)
if form.is_valid():
customer = form.save(commit=False)
customer.save()
context = {
'form': OrderForm()
}
messages.success(request, "Customer added successfully!")
return render(request, 'orders/add_order.html', context)
context = {'form': form}
return render(request, 'core/add_customer.html', context)
这是我的订单视图
def add_order(request):
form = OrderForm(request.POST or None)
orders = Order.objects.all()
if form.is_valid():
order = form.save(commit=False)
order.save()
messages.success(request, "Order placed")
return render(request, 'orders/index.html', {'orders': orders})
return render(request, 'orders/add_order.html', {'form': form})
这是我的模板
<a href="{% url 'core:add-customer' %}">
<p><em>Click this to add a new customer</em></p>
</a>
<form method="post">
{% csrf_token %}
{% include 'core/form-template.html' %}
<div align="center">
<button class="btn btn-success"> Submit </button>
</div>
</form>
但是,订单无法添加,因为它会抛出错误(需要此字段)
编辑:这是我的表格
OrderForm
class OrderForm(ModelForm):
class Meta:
model = Order
fields = ['customer']
CustomerForm
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = '__all__'
订单型号
class Order(models.Model):
customer = models.ForeignKey(Customer)
date_created = models.DateField(auto_now_add=True)
def __str__(self):
return str(self.customer)
客户模型
class Customer(models.Model):
company_name = models.CharField(max_length=250, unique=True)
contact_first_name = models.CharField(max_length=50)
contact_last_name = models.CharField(max_length=50)
contact_no = models.CharField(max_length=20)
email_address = models.EmailField()
address = models.CharField(max_length=400)
def __str__(self):
return self.company_name