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))
if form.is_valid():model_instance = form.save()
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)
return HttpResponseRedirect("/")
Best regards, Pavel