I have a similar use case where a formset can be either rendered by a standard http response or by a Ajax load.
My DRY solution is :
standard http response (the whole page)
The view instanciate the formset, render the template, but in it I have an {% include "path/to/formset-snippet.html %}
tag (surrounded by a with tag for reusability with the following).
AJAX response
I make a Ajax call to render a html fragment in the DOM node (say a ). In JQuery this is something like that :
$("#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>");
}
});
The view instanciate the same formset and render formset-snippet.html. Here an exemple of MyModel having images associated with :
@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))
Hope it can helps.