简体   繁体   中英

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? 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.

@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. 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. But this is much simpler and easy to maintain.

我能够使用karthikr答案以及我在stackoverflow Django表单上的该线程以及其他选项和freetext选项实现我想要的功能

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM