我有一个类似的用例,其中一个表单集可以通过标准 http 响应或 Ajax 加载呈现。
我的 DRY 解决方案是:
标准http响应(整个页面)
视图实例化表单集,渲染模板,但在其中我有一个{% include "path/to/formset-snippet.html %} 标记(由 with 标记包围,以便可重复使用以下内容)。
AJAX 响应
我进行 Ajax 调用以在 DOM 节点中呈现一个 html 片段(例如 a )。在 JQuery 中是这样的:
$("#my_container").load(url, function(response, status, xhr) {
if (status == "error") {
$(this).html("Sorry but there was an error: " +
xhr.status + " " + xhr.statusText +
'<div style="height:300px; overflow:scroll;">' +
response + "</div>");
}
});
视图实例化相同的表单集并呈现 formset-sn-p.html。这里是 MyModel 的示例,其中 images 与:
相关联
@login_required
def images_formset(request, object_id):
instance = MyModel.objects.get(pk=object_id)
prefix = request.GET.get('form_prefix', None)
formset = ImageMyModelFormSet(instance=instance, prefix=prefix)
return render_to_response('my_app/images_my_model_form_snippet.html', {
'images_my_model_formset': formset,
}, context_instance=RequestContext(request))
希望对您有所帮助。