Reputation: 319
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.
Upvotes: 0
Views: 1852
Reputation: 319
I was able to achieve what a I wanted using karthikr answer and also this thread on stackoverflow Django form with choices but also with freetext option?
Upvotes: 0
Reputation: 99680
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.
Upvotes: 1