Django handle new ManyToManyField items with get_or_create()

39 views
Skip to first unread message

Doc

unread,
Apr 14, 2015, 6:05:09 AM4/14/15
to django...@googlegroups.com
Help me, django-users, you're my only hope :D

Hi all, my name is Filippo, I'm from Italy and I'm totally stuck on this problem...

I have a model with a ManyToManyField and in my view I want to be able to add new options to the generated selectbox.

How can I handle those new items with get_or_create function?

I want to check for form validity before saving it, but it will never be valid because I have to create all the new ManyToMany items. In the meantime, I don't want to add new items if the form is not valid...

So I'm stuck with this not-working-code:

def add_entry(request):
    if request.method == 'POST':
        form = EntryForm(data=request.POST)
        model_instance = form.save(commit=False)
        for tag in model_instance.tags.all():
            t, created = Tag.objects.get_or_create(author=request.user, title=tag.title)
            model_instance.tags.add(t)
        if form.is_valid():
            model_instance.save()
            return HttpResponseRedirect("/")
    else:
        form = EntryForm()
    return render_to_response(
        'add_entry.html',
        {'form' : form },
        context_instance=RequestContext(request))

Pavel Kuchin

unread,
Apr 15, 2015, 7:55:59 AM4/15/15
to django...@googlegroups.com
Hi Filippo,

You can check is form valid or not, then if valid save related model and then add M2M objects, like this:

if form.is_valid():
  model_instance = form.save()
 for tag in model_instance.tags.all():
   t, created = Tag.objects.get_or_create(auth
or=request.user, title=tag.title)
   model_instance.tags.add(t)
 return HttpResponseRedirect("/")

Best regards, Pavel
Reply all
Reply to author
Forward
0 new messages