32

我有这两个模型:

模型.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

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

在此处输入图像描述

是否可以?

4

3 回答 3

37

这是我的简单解决方案:在模板中手动渲染 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>
于 2013-03-15T20:26:51.133 回答
13

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

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

楷模

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具有一个重写的initApp方法,该方法为模型表单的实例实例化一个 AppOption表单集。

最后,我们使用模型表单创建了一个模型App表单集。

这是保存所有应用程序和应用程序选项的视图

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>
于 2013-03-13T16:15:10.610 回答
8

对于那些希望以标准方式手动呈现 CheckBoxMultipleSelect 的人(Django 的方式,使用 HTML 列表),以下是我想出的(@below-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>
于 2017-02-10T05:46:47.090 回答