Styling ModelMultipleChoiceField Django
<p>I'm having trouble styling my django form with a ModelMultipleChoiceField.</p>

<p>Heres my form:</p>

<pre><code>class SkriptenSelect(forms.Form):
skripten = StyledModelMultipleChoiceField(
    queryset=None,
    widget=forms.CheckboxSelectMultiple,
)

def __init__(self, *args, **kwargs):
    choices = kwargs.pop('choices')
    super(SkriptenSelect, self).__init__(*args, **kwargs)
    self.fields['skripten'].queryset = choices

class StyledModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
    return mark_safe('&lt;ul class="list-inline" style="display: inline;"&gt;' \
                     '&lt;li&gt;{name}&lt;/li&gt;' \
                     '&lt;li&gt;{semester}&lt;/li&gt;' \
                     '&lt;li&gt;professor&lt;/li&gt;' \
                     '&lt;/ul&gt;'.format(name=escape(obj.name), semester=escape(obj.prefix))
                     )
</code></pre>

<p>And I used this for html:</p>

<pre><code>&lt;form action="." method="post"&gt;
  &lt;ul class="list-group"&gt;
    {% for skript in result_form.skripten %}
        &lt;li class="list-group-item"&gt;
            {{ skript }}
        &lt;/li&gt;
    {% endfor %}
&lt;/ul&gt;
{% csrf_token %}
&lt;input type="submit" value="Submit Selected" /&gt;
</code></pre>

<p></p>

<p>This requires me to put my HTML in my forms file, which is not a very mvc way. Also it restricts me heavily in how i can style the list (i.e making table of the model instance fields)</p>

<p>Is there anyway to make this smarter? I'd like to access {{ skript.name }}, {{ skript.checkbox }} or something in my {% for skript in result_form.skripten %} loop, but thats sadly not possible...</p>

<p>You can use <code>render_to_string</code>. It loads a template and renders it with a context. Returns a string.</p>

<pre><code>from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', {'foo': 'bar'})
</code></pre>

<p>For various variants you can make various StyledModelMultipleChoiceField subclasses OR pass the desired template_name when initialising the class. Eg:</p>

<pre><code>&gt;&gt;&gt; class FooField:
...     def __init__(self, template_name='default.html'):
...         self.template_name = template_name
...
&gt;&gt;&gt; x = FooField('table.html')
&gt;&gt;&gt; x.template_name
'table.html'
</code></pre>

<p>Use <code>self.template_name</code> where appropriate:</p>

<pre><code>def label_from_instance(self, obj)
    return render_to_string(self.template_name, {'foo': obj.foo})
</code></pre>

<p>If you want to display multiple instances, use a <a href="https://docs.djangoproject.com/en/1.10/topics/forms/formsets/" rel="nofollow">formset</a>.</p>

python html django