[英]Django form for a model create object of another model
Is there anyway to create an object of another model instance in a django form for a specified model? 无论如何,是否以Django形式为指定模型创建另一个模型实例的对象? For instance when you'll add a new user using django admin you have the options to create another group ou add the user to an existing one.
例如,当您使用django admin添加新用户时,您可以选择创建另一个组,也可以将该用户添加到现有用户中。
@Edit I will try to clarify better with another example ... I have a product form, to add a new product, the user can choose which category it belongs, but if there is no such category, it will have to create the corresponding category. @Edit我将尝试用另一个示例进行更好的说明...我有一个产品表格,添加一个新产品,用户可以选择它所属的类别,但是如果没有这样的类别,则必须创建相应的类别类别。 And then add this product to new category and save the new product.
然后将此产品添加到新类别并保存新产品。
if form.is_valid():
c = form.cleaned_data["category"]
category = Category.objects.filter(name=c).first()
if not category:
category = Category.objects.create(name=c)
product = form.save(commit=False)
product.category = category
product.save()
You could also consider using a pre_save
signal to create the category object. 您也可以考虑使用
pre_save
信号创建类别对象。 But this is much simpler and easy to maintain. 但这更简单,易于维护。
我能够使用karthikr答案以及我在stackoverflow Django表单上的该线程以及其他选项和freetext选项实现我想要的功能?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.