MagnusD MagnusD - 2 months ago 13
Python Question

POST data from modelform_factory generated form

What I'm trying to accomplish is to save the data to the relevant model. Very much looking to mimic the Django admin interface.

urls.py

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


view.py:

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})


add.html

Here I simply access
{{ formset }}
to get the relevant input fields.

Answer
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})

Something like that. You can read more about this in the docs: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#using-a-model-formset-in-a-view