Django - 在模板中单独渲染CheckboxSelectMultiple()小部件(手动)

时间:2013-03-10 15:11:31

标签: django django-forms

我有这两个模型:

models.py

class App(models.Model):
    app_name = models.SlugField(max_length=50)
    options_loaded = models.ManyToManyField(Option)
    created_by = models.ForeignKey(User)

    def __unicode__(self):
        return self.name

class Option(models.Model):
    option_name = models.SlugField(max_length=50)
    condition = models.BooleanField('Enable condition')
    option = models.BooleanField('Enable option1')
    created_by = models.ForeignKey(User)

    def __unicode__(self):
        return self.option_name

我想渲染一个看起来像这样的表单,其中复选框来自不同的模型(带有CheckboxSelectMultiple()小部件的M2M字段的第一列),Option_name可能是<a href="/link/">Option_name</a>

enter image description here

有可能吗?

3 个答案:

答案 0 :(得分:32)

这是我的简单解决方案:在模板中手动渲染CheckboxSelectMultiple()

<table>
<thead>
  <tr>
    <td>&nbsp;</td>
    <td>V</td>
    <td>S</td>
  </tr>
</thead>    
{% for pk, choice in form.options.field.widget.choices %}
<tr>
  <td><a href="/link/{{ choice }}">{{ choice }}</a></td>
  <td>
    <label for="id_options_{{ forloop.counter0 }}">
      <input {% for m2moption in model.m2moptions.all %}{% if option.pk == pk %}checked="checked"{% endif %}{% endfor %} type="checkbox" id="id_options_{{ forloop.counter0 }}" value="{{ pk }}" name="options" />
    </label>
  </td>
</tr>
{% endfor %}                
</table>

答案 1 :(得分:12)

http://dev.yaconiello.com/playground/example/one/

首先,我会像这样重组你的模型。您当前设置的方式,选项/应用程序复选框关系将表现不佳。每个Option只能拥有一个与所有App对象共享的布尔选中值。

模型

from django.db import models
from django.utils.translation import ugettext as _

class Option(models.Model):
    condition = models.CharField(
        verbose_name = _(u'Condition Text'),
        max_length = 255,
    )
    option = models.CharField(
        verbose_name = _(u'Option Text'),
        max_length = 255,
    )

    def __unicode__(self):
        return self.condition


class App(models.Model):
    title = models.CharField(
        verbose_name = _(u'App Name'), 
        max_length = 255
    )
    slug = models.SlugField(
        max_length = 50,
        unique = True
    )
    activated = models.BooleanField(
        verbose_name = _(u'Activated'),
        default = False,
    )
    options = models.ManyToManyField(
        Option,
        through="AppOption"
    )

    def __unicode__(self):
        return self.title


class AppOption(models.Model):
    app = models.ForeignKey(
        App,
        verbose_name = _(u'App'), 
    )
    option = models.ForeignKey(
        Option,
        verbose_name = _(u'Option'), 
    )
    condition_activated = models.BooleanField(
        verbose_name = _(u'Condition Activated'),
        default = False,
    )
    option_activated = models.BooleanField(
        verbose_name = _(u'Option Activated'),
        default = False,
    )

    class Meta:
        unique_together = (("app", "option"),)

    def __unicode__(self):
        return "%s %s (%s | %s | %s)" % (self.app, self.option, self.app.activated, self.option_activated, self.condition_activated)

其次,您应该使用内部自定义逻辑的模型表单集和模型表单...

形式

from django.forms.models import modelformset_factory
from django import forms

class AppOptionForm(forms.ModelForm):
    class Meta:
        model = AppOption
        fields = ("app", "option", "condition_activated", "option_activated")

AppOptionFormSet = modelformset_factory(AppOption, form=AppOptionForm)

class AppForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(AppForm, self).__init__(*args, **kwargs)

        if self.instance:
            self.appoptions_prefix = "appoptions-%s"%self.instance.pk
            self.appoptions_formset = AppOptionFormSet(prefix=self.appoptions_prefix, 
                queryset=AppOption.objects.filter(app=self.instance).order_by('option'))

    class Meta:
        model = App
        fields = ("id", "activated",)

AppFormSet = modelformset_factory(App, form=AppForm)

好的,刚刚发生的事情是我们为AppOption创建了一个模型,然后将其转换为模型形式。

然后,我们为App创建了一个模型表单,其中包含一个重写的 init 方法,该方法为App模型表单的实例实例化AppOption表单集。

最后,我们使用App modelform创建了一个modelformset。

这是一个保存所有应用和应用的视图

def one(request):
    if request.method == 'POST':
        formset = AppFormSet(request.POST, prefix="apps") # do some magic to ALSO apply POST to inner formsets
        if formset.is_valid(): # do some magic to ALSO validate inner formsets
            for form in formset.forms:
                # saved App Instances
                form.save()
                for innerform in form.appoptions_formset:
                    # saved AppOption instances
                    innerform.save()
    else:
        formset = AppFormSet(prefix="apps")

    options = Option.objects.all()

    return render(
        request,
        "playground/example/one.html",
        {
            'formset' : formset,
            'options' : options,
        }
    )

模板

this is a test
<style>
thead td {
    width: 50px;
    height: 100px;
}
.vertical {
    -webkit-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -ms-transform: rotate(-90deg);
    -o-transform: rotate(-90deg);
    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
</style>
<form>
<table>
<thead>
    <tr>
        <td>&nbsp;</td>
        <td><p class="vertical">Activate App</p></td>
        {% for option in options %}
        <td><p class="vertical">{{ option.condition }}</p></td>
        <td><p class="vertical">{{ option.option }}</p></td>
        {% endfor %}
    </tr>
</thead>
{% for form in formset.forms %}
    {% if form.instance.pk %}
    <tr>
        <td align="center">{{ form.instance.title }}{{ form.id.as_hidden }}</td>
        <td align="center">{{ form.activated }}</td>
        {% for optionform in form.appoptions_formset.forms %}
        {% if optionform.instance.pk %}
        <td align="center">
            {{ optionform.app.as_hidden }}
            {{ optionform.app.as_hidden }}
            {{ optionform.condition_activated }}
        </td>
        <td align="center">{{ optionform.option_activated }}</td>
        {% endif %}
        {% endfor %}
    </tr>
    {% endif %}
{% endfor %}
</table>
</form>

答案 2 :(得分:3)

对于那些来到这里寻找手工渲染CheckBoxMultipleSelect但是以标准方式(Django的方式,使用HTML列表)的人来说,以下是我提出的(@ under-the-radar的解决方案帮助我实现了它)

<ul id="id_{{field.name}}">
  {% for pk, choice in field.field.widget.choices %}
    <li>
      <label for="id_{{field.name}}_{{ forloop.counter0 }}">
      <input id="id_{{field.name}}_{{ forloop.counter0 }}" name="{{field.name}}" type="checkbox" value="{{pk}}" />
      {{ choice }}
      </label>
    </li>
  {% endfor %}
</ul>