Login

ManyToMany field with newforms

Author:
lawgon
Posted:
November 25, 2007
Language:
Python
Version:
.96
Tags:
newforms multiplechoicefield manytomany
Score:
0 (after 0 ratings)

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

  1. Clone model mixin by zakj 6 years, 6 months ago
  2. newforms: Add field-specific error in form.clean() by miracle2k 7 years, 11 months ago
  3. Newforms customs validators by baptiste 8 years, 3 months ago
  4. Limit ManyToMany fields in forms by jedie 5 years, 10 months ago
  5. Using Akismet/TypePad AntiSpam with Django's new comments framework by sciyoshi 6 years, 10 months ago

Comments

Please login first before commenting.