如何在不破坏表单的情况下在选项旁边呈现ChoiceField图像?

时间:2015-08-19 07:47:06

标签: python html django django-forms

我试图在他们各自的选择旁边呈现选择的图像。试图这样做不会将表格保存为有效,所以我不知道该做什么。我已尝试过以下两种方法,我不知道为什么一种方法有效,另一种方法无效,我可以获得一些提示吗?

#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>    

1 个答案:

答案 0 :(得分:1)

字段的name属性不应为{{ x }}。它应该是"servergroups"

请注意,您还需要一些逻辑来确定是否已选择该字段,例如,在验证错误后重新显示表单时。