Django内联formset:form.visible_fields中的DELETE字段?

时间:2013-08-16 20:48:51

标签: django django-forms

也许有人可以向我解释一下。

使用以下型号:

class ContactEmail(models.Model):
    # Documentation
    __doc__ = _(u'Stores an e-mail address for a contact.')
    # Enums
    CATEGORIES = (
        (0, _(u'Personal')),
        (1, _(u'Professional')),
    )
    # Attributes
    category = models.IntegerField(choices=CATEGORIES, verbose_name=_(u'category'), help_text=_(u'This values indicates wheter the address is for personal or professional use.'))
    email_address = models.EmailField(max_length=255, unique=True, verbose_name=_(u'e-mail address'), help_text=_(u'A valid e-mail address.'))
    contact = models.ForeignKey('Contact', related_name=u'emails', verbose_name=_(u'contact'), help_text=_(u'The contact whose the e-mail address is.'))
    priority_level = models.PositiveSmallIntegerField(verbose_name=_(u'priority level'), help_text=_(u'An integer used to define a priority level for e-mail addresses of a contact.'))

    # Methodes
    def __unicode__(self):
        return u'%(mail)s' % {u'mail': self.email_address}

    # Meta-data
    class Meta:
        verbose_name = _(u'E-mail')
        verbose_name_plural = _(u'E-mails')
        unique_together = ('contact', 'priority_level')

class Contact(models.Model):
    pass

以下的ModelForms:

class ContactCreateForm(forms.ModelForm):
    # Documentation
    __doc__ = _(u'A custom form for Contact model.')

    # Methods
    def __init__(self, *args, **kwargs):
        super(ContactCreateForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if name != 'image':
                if field.widget.attrs.has_key('class'):
                    field.widget.attrs['class'] += ' form-control'
                else:
                    field.widget.attrs.update({'class':'form-control'})

    # Meta-data
    class Meta:
        model = Contact
        exclude = ['second_names', 'suffix', 'dob', 'skype_account',]

class ContactEmailCreateForm(forms.ModelForm):
    # Documentation
    __doc__ = _(u'A custom form for ContactEmail model.')

    # Methods
    def __init__(self, *args, **kwargs):
        super(ContactEmailCreateForm, self).__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if field.widget.attrs.has_key('class'):
               field.widget.attrs['class'] += ' form-control'
            else:
                field.widget.attrs.update({'class':'form-control'})

    # Meta-data
    class Meta:
        model = ContactEmail

我正在尝试设置一个包含电子邮件表单集的创建联系表单(意图是使用django-dynamic-formset动态添加表单,就像管理员一样 - 并确保它有效)。以下是观点:

class ContactCreateView(LoginRequiredMixin, CreateView):
    template_name = u'frontend/contacts/create.html'
    model = Contact
    form_class = ContactCreateForm

    def get_context_data(self, **kwargs):
        context = {
            'emails' : inlineformset_factory(parent_model=Contact, model=ContactEmail, form=ContactEmailCreateForm, extra=1),
        }
        context.update(kwargs)
        return super(ContactCreateView, self).get_context_data(**context)

django-dynamic-formset 要求您设置默认情况下在inlineformset_factory中设置的can_delete=True。此参数会为表单集的每种形式添加 DELETE字段

直到这里,没有什么值得抱怨的。除非它将此字段添加到form.visible_fields,即IMO,这种情况令人不安,因为如果没有form.instance则隐藏此字段:

# create.html
<fieldset class="emails">
    <legend>{% trans "E-mail(s)" %}</legend>
    {{ emails.management_form }}
    {% for form in emails %}        
    <div class="inline-form-emails">
        {{ form.media }}
        {% for hidden in form.hidden_fields %}
        {{ hidden }}
        {% endfor %}
        {% for field in form.visible_fields %}
        <div class="form-group">
            <label for="{{ field.html_name }}" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
                {{ field.label }} {% if field.field.required %}<span style="color: #a60000;">*</span>{% endif %}
            </label>
            <div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
                {{ field }}
                <span class="help-block">{{ field.help_text }}</span>
            </div>
        </div>
        {% endfor %}
    </div>
    {% endfor %}
</fieldset>

如您所见:

<fieldset class="emails">
    <legend>E-mail(s)</legend>
    <input id="id_emails-TOTAL_FORMS" name="emails-TOTAL_FORMS" type="hidden" value="1"><input id="id_emails-INITIAL_FORMS" name="emails-INITIAL_FORMS" type="hidden" value="0"><input id="id_emails-MAX_NUM_FORMS" name="emails-MAX_NUM_FORMS" type="hidden" value="1000">

    <div class="inline-form-emails dynamic-form">


        <input id="id_emails-0-contact" name="emails-0-contact" type="hidden">

        <input id="id_emails-0-id" name="emails-0-id" type="hidden">


        <div class="form-group">
            <label for="emails-0-category" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
                Category <span style="color: #a60000;">*</span>
            </label>
            <div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
                <select class="form-control" id="id_emails-0-category" name="emails-0-category">
                    <option value="" selected="selected">---------</option>
                    <option value="0">Personal</option>
                    <option value="1">Professional</option>
                </select>
                <span class="help-block">This values indicates wheter the address is for personal or professional use.</span>
            </div>
        </div>

        <div class="form-group">
            <label for="emails-0-email_address" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
                E-mail address <span style="color: #a60000;">*</span>
            </label>
            <div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
                <input class="form-control" id="id_emails-0-email_address" maxlength="255" name="emails-0-email_address" type="text">
                <span class="help-block">A valid e-mail address.</span>
            </div>
        </div>

        <div class="form-group">
            <label for="emails-0-priority_level" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
                Priority level <span style="color: #a60000;">*</span>
            </label>
            <div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
                <input class="form-control" id="id_emails-0-priority_level" name="emails-0-priority_level" type="text">
                <span class="help-block">An integer used to define a priority level for e-mail addresses of a contact.</span>
            </div>
        </div>

        <div class="form-group">
            <label for="emails-0-DELETE" class="col-xs-12 col-sm-5 col-md-3 col-lg-3 control-label">
                Delete 
            </label>
            <div class="col-xs-12 col-sm-7 col-md-9 col-lg-9">
                <input type="hidden" name="emails-0-DELETE" id="id_emails-0-DELETE">
                <span class="help-block"></span>
            </div>
        </div>

    <a class="delete-row" href="javascript:void(0)">remove</a></div><a class="add-row" href="javascript:void(0)">add another</a>

</fieldset>

任何人都有线索?

1 个答案:

答案 0 :(得分:1)

如上所述here,问题来自django-dynamic-form库!

以防有人陷入同一个陷阱...