简体   繁体   中英

Django Formset adding two rows instead of one with same input id

I'm trying to implement dynamic formset using django. It is working properly except that it adds two rows of input field with same ID when add button is clicked. ony one row is supposed to be added.

models.py

class StaffEmailCC(BaseModel):
    staff_email = models.ForeignKey("projects.StaffEmail",blank=True,null=True)
    cc_addresses=models.TextField(blank=True,null=True)
    class Meta:
        db_table = 'staffmailcc'
        verbose_name = _('staffmailcc')
        verbose_name_plural = _('staffmailcc')
        ordering = ('-date_added',)
    def __unicode__(self):
        return self.cc_addresses

forms.py

class StaffEmailCCForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(StaffEmailCCForm, self).__init__(*args, **kwargs)
    class Meta:
        model = StaffEmailCC
        fields = ['cc_addresses']
        widgets = {
            'cc_addresses': autocomplete_light.ChoiceWidget('StaffAutocomplete'),
        }

views.py

def create_staff_mail(request):
    StaffEmailCCFormset = formset_factory(StaffEmailCCForm)
    staff_email_cc_formset = StaffEmailCCFormset(prefix='staff_email_cc_formset')
    form = StaffEmailForm()
    context = {
        "form": form,
        "staff_email_cc_formset":staff_email_cc_formset,
        "title": "Create Staff Mail",
        "sender_email":sender_email,
            }
    return render(request, 'projects/create_staff_mail.html', context)

HTML

<div class="content formElements add_item_container staff_email_cc_formset">
            <table>
                <tr>
                    <th>CC</th>
                </tr>
                {% for i in staff_email_cc_formset.forms %}
                <tr class="form_set_row">
                        <td>
                            <span class="left cc_addresses">
                                {{i.cc_addresses}}
                            </span>
                        </td>
                </tr>
                  {% endfor %}
             </table>
        {{ staff_email_cc_formset.management_form }}
    </div>

js

$('.staff_email_cc_formset table tr.form_set_row').formset({
                prefix: '{{ staff_email_cc_formset.prefix }}',
                formCssClass: 'dynamic-formset1'
            }); 

Each time i click the add button, two rows are added, out of which only one row working correctly with autocomplete. any idea what i' doing wrong?

Django formsets have extra=1 as default.

[...]The number of empty forms that is displayed is controlled by the extra parameter. By default, formset_factory() defines one extra form[...]

Documentation : search for extra= in the page to quickly find what you're looking for.

StaffEmailCCFormset = formset_factory(StaffEmailCCForm, extra=0)

you can assign fields to formset,

if you write formset like this, it takes extra field default 1:

StaffEmailCCFormset = formset_factory(StaffEmailCCForm)

you overwrite extra field StaffEmailCCFormset = formset_factory(StaffEmailCCForm, extra=1)

you can see source code of formset.py https://github.com/django/django/blob/master/django/forms/formsets.py

This might seem weird. but putting the js function inside $(document).ready(function (){}); solved my issue

$(document).ready(function () {
        $('.staff_email_cc_formset table tr.form_set_row').formset({
            prefix: '{{ staff_email_cc_formset.prefix }}',
            formCssClass: 'dynamic-formset1'
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM