In editing a ManyToMany field in a form, it is necessary to clear the entries in the bridge table before adding new entries. So first save the new entries, remove the old entries in the multiple choice field and then add the new entries. It is also necessary to add the commit_on_success decorator to make sure that the whole process is in one transaction.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | class Edittalkform(forms.Form):
def __init__(self, *args, **kwargs):
self.fields['speaker'].choices = [(chld.id,
chld.username) for chld in Delegate.objects.all()]
title = forms.CharField(max_length=250,
label=_("Talk Title")
)
speaker = forms.MultipleChoiceField(label=_("Speaker(s)"),
choices=()
)
@user_passes_test(lambda u: u.is_anonymous()==False ,login_url="/web/login/")
@transaction.commit_on_success
def edittalk(request,id):
if request.POST:
form = Edittalkform(request.POST)
if form.is_valid():
fm = form.cleaned_data
delgid = Delegate.objects.get(username=request.user).id
if str(delgid) not in fm['speaker']:
form.errors['speaker'] = [_("Your own username\
is missing from the list of speakers")]
if not form.errors:
newtalk.title = fm['title']
newtalk.save()
# remove all the previous speakers
newtalk.speaker.clear()
for spk in fm['speaker']:
newtalk.speaker.add(Delegate.objects.get(pk=int(spk)))
return HttpResponseRedirect("/web/talks/" )
else:
tlk = Talk.objects.get(pk=id)
data = {
'title': tlk.title,
'speaker': [p.id for p in tlk.speaker.all()],
}
form = Edittalkform(data)
return render_to_response("web/edittalk.html",
{'form':form,
'request':request
})
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.