[Fixed]-Django form for a model create object of another model

1👍

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.

0👍

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?

Leave a comment