来自modelform_factory的POST数据生成表单

时间:2016-10-05 19:33:20

标签: python django python-2.7 django-models django-forms

我想要完成的是将数据保存到相关模型。非常希望模仿Django管理界面。

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

在这里,我只需访问{{ formset }}即可获取相关的输入字段。

1 个答案:

答案 0 :(得分:0)

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

这样的事情。您可以在文档中详细了解相关内容:https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#using-a-model-formset-in-a-view