Django - Checkboxes for Models, Two Submit Buttons_ Add Person Model to Group Model, Reject Person...

3
12/6/2014 django - Checkboxes for models, two su bmit b uttons : add per son model to gr oup model, rej ect p erson model from gro… http://stackoverflow.com/ques tion s/2134341/c hec kboxes-for- models -two-su bmit -but tons -add-p ers on-model -to-gr oup-mod el-r eje 1/3 Take the 2-minute tour  × Clash 1,036  14 28 I've looked at formset and model formset at Django many times, but I still can't figure the smart way to do this. I have two models: Group Person I have a queryset that contains all the persons trying to join a particular group: Person.objects. filter(wantsToJo inGroup=groupD) Now, what I want to do, is display a page with a checkbo x at the side of each person that wants to join a particular group. Those checkboxes can then be checke d and then the button 'Accept to Group' is clicked. I want this to bulk add those persons to a certain group. What I fail to understand how to do is exactly the checkbox thing. I've bee n trying to extend a modelform and then make a formset out of it, but I fail at it everytime. It seems like if I want to do a formset with models I should use modelformset , but that does not all ow me to extend the form to add a checkbox. How can I do it? Here is a 10-second draft on paint of what I would like to have: So it's basically, a checkbox and a way to access the person model at the template and then a way to proccess this on the view. Thanks in advance! Edit: By the way, before someone suggests using ModelMultipleChoiceField , unless there is a way to access each of the objects inside it on the template, this will not fulfill what I need to do. As far as I know, I can't iterate over the objects of ModelMultipleChoiceField on the template. Please correct me if I'm wrong! django  django-models  django-forms edited Jan 25 '10 at 18:37  asked Jan 25 '10 at 17:51 Stack Overflow is a questi on and answer site for professional and enthusiast programmers. It's 100% free, no registrati on required. Checkboxes for models, two submit buttons: add person model to g roup model, reject person model from group model sign up log in tour help careers 2.0  

Transcript of Django - Checkboxes for Models, Two Submit Buttons_ Add Person Model to Group Model, Reject Person...

  • 12/6/2014 django - Checkboxes for models, two submit buttons: add person model to group model, reject person model from gro

    http://stackoverflow.com/questions/2134341/checkboxes-for-models-two-submit-buttons-add-person-model-to-group-model-reje 1/3

    Takethe2minutetour

    Clash1,036 14 28

    I'velookedatformsetandmodelformsetatDjangomanytimes,butIstillcan'tfigurethesmartwaytodothis.

    Ihavetwomodels:

    Group

    Person

    Ihaveaquerysetthatcontainsallthepersonstryingtojoinaparticulargroup:Person.objects.filter(wantsToJoinGroup=groupD)

    Now,whatIwanttodo,isdisplayapagewithacheckboxatthesideofeachpersonthatwantstojoinaparticulargroup.Thosecheckboxescanthenbecheckedandthenthebutton'AccepttoGroup'isclicked.Iwantthistobulkaddthosepersonstoacertaingroup.

    WhatIfailtounderstandhowtodoisexactlythecheckboxthing.I'vebeentryingtoextendamodelformandthenmakea formsetoutofit,butIfailatiteverytime.ItseemslikeifIwanttodoaformsetwithmodelsIshoulduse modelformset,butthatdoesnotallowmetoextendtheformtoaddacheckbox.HowcanIdoit?

    Hereisa10seconddraftonpaintofwhatIwouldliketohave:

    Soit'sbasically,acheckboxandawaytoaccessthepersonmodelatthetemplateandthenawaytoproccessthisontheview.

    Thanksinadvance!

    Edit:Bytheway,beforesomeonesuggestsusing ModelMultipleChoiceField,unlessthereisawaytoaccesseachoftheobjectsinsideitonthetemplate,thiswillnotfulfillwhatIneedtodo.AsfarasIknow,Ican'titerateovertheobjectsofModelMultipleChoiceFieldonthetemplate.PleasecorrectmeifI'mwrong!

    django djangomodels djangoforms

    editedJan25'10at18:37 askedJan25'10at17:51

    StackOverflowisaquestionandanswersiteforprofessionalandenthusiastprogrammers.It's100%free,noregistrationrequired.

    Checkboxes for models, two submit buttons: add person model to group model, rejectperson model from group model

    signup

    login

    tour

    help

    careers2.0

  • 12/6/2014 django - Checkboxes for models, two submit buttons: add person model to group model, reject person model from gro

    http://stackoverflow.com/questions/2134341/checkboxes-for-models-two-submit-buttons-add-person-model-to-group-model-reje 2/3

    3 Answers

    DrBloodmoney1,848 2 9 15

    DmitryShevchenko10.9k 4 26 38

    dannyroa1,951 1 11 35

    Ifyou'renotmarriedtotheideaofusingamodelform,Iwouldjustusearegularform,withaModelMultipleChoiceField,giveitaquerysetinthe __init__thenprovidethatsamequerysettothetemplatecontext(toiterateoveratyourleisure):

    #viewdefadd_to_group(request):persons=Person.objects.filter(wantsToJoinGroup=groupD)ifrequest.POST:form=PersonAddForm(persons,request.POST)ifform.is_valid():#yourhandlinglogicform=PersonAddForm(persons)context={'persons':persons,'form':form}returnrender_to_response(template,context)

    #formclassPersonAddForm(forms.Form):def__init__(self,queryset,*args,**kwargs):super(PersonAddForm,self).__init__(*args,**kwargs)self.fields['persons']=forms.ModelMultipleChoiceField(queryset=queryset,widget=forms.CheckboxSelectMultiple())

    editedJan25'10at22:54 answeredJan25'10at19:50

    Hello!Thankyouforyouranswer!I'mtryingyoursolution,butmyformisalwaysreturingfalseforis_valid(),anyideawhy? Clash Jan25'10at22:28

    JustfiguredIneededtopassrequest.POSTandquerysetargtotheform...bytheway,neededtousekwargs.pop('queryset',None)togetittowork,thanks! Clash Jan25'10at22:48

    Youshouldn'thavetopopit,becauseyouarepassingitasapositionalargumentandnotakeyword.Iusethispatternagoodbit.You'llhavetopasstherequest.POSTtotheformtovalidate(onPOSTobviously),butnotonget.I'lledittobeexplicit.DrBloodmoneyJan25'10at22:54

    Ah,Isee,soIsenditasanonkeywordedarg!Thankyou Clash Jan25'10at23:03

    YoucanactuallygettoModelMultipleChoiceField'sitemsthisway:

    my_field.field.queryset

    wheremy_fieldisaninstanceofModelMultipleChoiceField.

    answeredJan25'10at20:09

    Thankyouforyouranswer! Clash Jan25'10at22:29

    Atthetopofmyhead,youcaninsertahiddenfieldcalled'Action'.OntheonclickeventoftheAcceptandRejectbuttons,setthevalueofthehiddenfieldappropriatelyandthensubmittheform.

    Inyourview,checkthevalueofthehiddenfieldtofigureoutifit'sAcceptorReject.

    answeredJan25'10at18:16

    HelloDanny,thankyouforanswer...IwaslookingforsomethingontheDjangoside,nojavascriptinvolvedpreferentiallyRegardingthecheckboxes,howcantheybedone? Clash Jan25'10at18:18

    Notsureifthatispossiblewithoutjavascriptbecauseyoucannotselectivelysubmitformfields.Ifyoudon'twantjavascript,makeAcceptandRejectradiobuttonsandhaveaseparatesubmitbutton.dannyroaJan25'10at20:28

    addcomment

    addcomment

    addcomment

    addcomment

  • 12/6/2014 django - Checkboxes for models, two submit buttons: add person model to group model, reject person model from gro

    http://stackoverflow.com/questions/2134341/checkboxes-for-models-two-submit-buttons-add-person-model-to-group-model-reje 3/3

    Not the answer you're looking for? Browse other questions tagged django

    django-models django-forms or ask your own question.