Kalijix
Kalijix

Reputation: 35

How do I render form ChoiceField images next to choices without breaking the form?

I am trying to render the images of the choices next to their respective choice. Attempting to do so will not save the form as valid so I have become lost at what to do. I've tried both methods below and I have no idea why one works and the other doesn't, could I get some tips?

#Form:

    class ServerGroupForm(forms.Form):
        OPTIONS = (
            ("pic1", "https://i.imgur.com/tMahp6U.png"),
            ("pic2", "https://i.imgur.com/b76nwsj.gif"),
            ("pic3", "https://i.imgur.com/qzEcfyX.png Lover"),
            ("pic4", "https://i.imgur.com/kdc7UF7.png"),
            ("pic5", "https://i.imgur.com/ynWJ13W.gif"),
            ("pic6!", "https://i.imgur.com/goHFWsp.png"),
            ("pic7", "https://i.imgur.com/b76nwsj.gif"),
            ("pic8", "https://i.imgur.com/KPgKm79.png"),
            ("pic9", "https://i.imgur.com/7KtEV1i.png"),
            ("pic10", "https://i.imgur.com/7KtEV1i.png"),
            ("pic11", "https://i.imgur.com/FXfo773.png")
        )
        servergroups = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OPTIONS)    
#View:
    def sendmessage(msg):
        #Other code sends msg to user, not includes so this isn't long
    def select_server_group(request):
        form = ServerGroupForm(request.POST)
        if form.is_valid():
            servergroups = form.cleaned_data['servergroups']
            sendmessage(msg=servergroups)
            return redirect('/')
        return render_to_response('webts3/selcectsgroup.html', {'form':form },
            context_instance=RequestContext(request))    

#HTML: Works but no icons
    <section class="login">
        <div class="titulo">Create a channel</div>
        <form method="post" action="." enctype="multipart/form-data">{% csrf_token %}
            <table border="0">
                {{ form.as_table }}
            </table>
            <input type="submit" class="btn btn-block btn-danger" value="Submit" style="margin-top: 10px;">
         </form>
    </section>    
#HTML: Icons but not working
    <form method='post' action="." enctype="multipart/form-data">{% csrf_token %}>
        <table>
            {% for x,y in form.fields.servergroups.choices %}
            <tr>
                <td><input type="checkbox" name="{{ x }}" value="{{ x }}"><img src={{ y }}</img></td>
            </tr>
        {% endfor %}
    </table>
    <input type='submit' value='submit'>
</form>    

Upvotes: 1

Views: 786

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599628

The name attribute of the field should not be {{ x }}. It should be "servergroups".

Note you'd also need to have some logic that determines if the field is already selected, for when for example the form is being redisplayed after validation errors.

Upvotes: 1

Related Questions