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
- Form field with fixed value by roam 1 week ago
- New Snippet! by Antoliny0919 1 week, 6 days ago
- Add Toggle Switch Widget to Django Forms by OgliariNatan 3 months ago
- get_object_or_none by azwdevops 6 months, 3 weeks ago
- Mask sensitive data from logger by agusmakmun 8 months, 2 weeks ago
Comments
Please login first before commenting.