POST data from modelform_factory generated form
<p>What I'm trying to accomplish is to save the data to the relevant model. Very much looking to mimic the Django admin interface.</p>

<p>urls.py   </p>

<pre><code>url(r'^admin/add/(\w+)', views.admin_add_object, name='admin_add_object'),
</code></pre>

<p>view.py: </p>

<pre><code>def admin_add_object(request, model):
if request.method == "POST":
    # The code I need to save the posted data
else:
    model_name = apps.get_model("product", model)
    ModelFormSet = modelform_factory(model_name, fields=("__all__"))
    return render(request, 'product/admin/add.html', {'formset': ModelFormSet})
</code></pre>

<p>add.html</p>

<p>Here I simply access <code>{{ formset }}</code> to get the relevant input fields.</p>

<pre><code>def admin_add_object(request, model):
    model_name = apps.get_model("product", model)
    ModelFormSet = modelformset_factory(model_name)
    if request.method == 'POST':
        formset = ModelFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
            # do something fancy. Redirect or so...
    else:
        ModelFormSet = modelform_factory(model_name, fields=("__all__"))
        return render(request, 'product/admin/add.html', {'formset': ModelFormSet})
</code></pre>

<p>Something like that. You can read more about this in the docs: <a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#using-a-model-formset-in-a-view" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#using-a-model-formset-in-a-view</a>   </p>

python django python-2.7 django-models django-forms