简体   繁体   中英

Django formset - not setting initial data when data is passed

I am creating form using Django Form wizard and formsets.

def get_form(self, step=None, data=None, files=None):
initial_data_set = []
for x in some_list:
     initial_data_set.append({
                        'title' : x.title,
                    })
data = {
'form-TOTAL_FORMS': '5',
'form-INITIAL_FORMS': '5',
'form-MAX_NUM_FORMS': '',
 }
formset_class = formset_factory(TitleForm, extra =0)
formset =  formset_class(data=data, initial=initial_data_set)
return formset

Template

{% extends "admin/base_site.html" %}
{% load i18n %}


{% block content %}
{% if wizard.form.forms %}
    {% for form in wizard.form.forms %}
        {{ form.media }}
    {% endfor %}
{% else %}
    {{ wizard.form.media }}
{% endif %}
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="." method="post" enctype="multipart/form-data">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
    {{ wizard.form.management_form }}
    {% for form in wizard.form.forms %}
        {% if ingestable_upload %}
            <tr>{{ form.as_inline_table }}</tr>
        {% else %}
            {{ form.as_table }}
        {% endif %}
    {% endfor %}
{% else %}
    {{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
<input type="submit" value="{% trans "Submit" %}"/>
</form>
{% endblock %}

I was able to see initial data in my form when I was not passing 'data'. However, not passing data was giving me formset.is_valid as False and there was None in the cleaned_data. So I created data{} and passed it as per the documentation here - https://docs.djangoproject.com/en/1.7/topics/forms/formsets/#understanding-the-managementform

Since I started passing data, form is not getting populated with initial data. I have put debug statements in formsets.py under BaseFormSet() class. It is getting both data and initial data that I am passing.

I have been struggling with this for few days. Any help on how I can populate my form and get cleaned data will be great.

What you're doing is overriding your form initial data with your data object, data attribute is not necessary that data is passed on the {{ formset.management_form }} in your template.

There's something else wrong with your form. I would suggest you print the errors when is_valid fails and see what's missing.

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