Tuesday, April 14, 2015

Django handle new ManyToManyField items with get_or_create()

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))

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a007aee0-4ecd-428d-8636-afcdca286a38%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment