[英]How would I create a form for a foreign key field that has a drop down menu with an 'add item' option in django?
I'll start with my model fields: 我将从模型字段开始:
class Store(models.Model):
name = models.CharField(max_length=250)
def __str__(self):
return self.name
class Product(models.Model):
type = models.CharField(max_length=250)
def __str__(self):
return self.type
class Receipt(models.Model):
store = models.ForeignKey(Store)
date = models.DateField()
line_items = models.ManyToManyField(Product, through='ReceiptProduct')
def __str__(self):
return self.store.name + ': ' + str(self.date)
class ReceiptProduct(models.Model):
receipt = models.ForeignKey(Receipt)
product = models.ForeignKey(Product)
price = models.FloatField()
description = models.CharField(max_length=500, null=True, blank=True)
def __str__(self):
return self.product.type
What I would like to do is create a form for the ReceiptProduct model. 我想做的是为ReceiptProduct模型创建一个表单。
class AddItemForm(ModelForm):
class Meta:
model = ReceiptProduct
fields = ['product', 'price', 'description']
Done. 做完了 And the view? 和看法?
def add_receipt_product(request, receipt_id):
current_receipt = Receipt.objects.get(id=receipt_id)
if request.method != 'POST':
# No data submitted; create a blank form.
form = AddItemForm(initial={'receipt': current_receipt})
else:
# POST data submitted; process data.
form = AddItemForm(data=request.POST)
if form.is_valid():
new_product = form.save(commit=False)
new_product.receipt = current_receipt
new_product.save()
return HttpResponseRedirect(reverse('purchase_log:receipt_details', args=[receipt_id]))
context = {'current_receipt': current_receipt, 'form': form}
return render(request, 'purchase_log/add_receipt_product_form.html', context)
Okay, so what I would like to do is, under the 'product' field (which is a drop down menu populated by the Product model), have an option called, maybe, 'custom product' or something, that the user can select to add an item to the Product model and will then appear in future drop down menus. 好的,所以我想做的是,在“产品”字段(这是产品模型填充的下拉菜单)下,有一个名为“定制产品”的选项,用户可以选择将产品添加到产品模型中,然后将出现在以后的下拉菜单中。 Is this do-able? 这可行吗?
Thank you all in advanced!! 谢谢大家先进!
Django implements this in terms of a "formset" . Django 通过“ formset”来实现这一点。 Check out this tutorial for additional information: http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html I think the example there is fairly similar to yours. 请查看此教程以获取更多信息: http : //whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html我认为那里的示例与您的示例非常相似。
In the Django admin interface, things are somewhat easier, and you can use an Inline
. 在Django管理界面中,事情有些简单,您可以使用Inline
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.