Login

ManyToMany field with newforms

Author:
lawgon
Posted:
November 25, 2007
Language:
Python
Version:
.96
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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 2 months, 2 weeks ago
  2. Python Django CRUD Example Tutorial by tuts_station 3 months ago
  3. Browser-native date input field by kytta 4 months, 2 weeks ago
  4. Generate and render HTML Table by LLyaudet 4 months, 4 weeks ago
  5. My firs Snippets by GutemaG 5 months ago

Comments

Please login first before commenting.