0

How can I go about implementing the following use case with AJAX? I read this question which was the closest I could find to my use case but I'm still unsure on how to get started.

Use Case

I enter a quantity number, say '3', into an input text field for a ticket item. After entering this value, 3 formsets appear below with an email field.

Conceptually, I'm thinking, on the change of the input value, load the django formset variable like

    {% for form in formset %}
    {{ form }}
    {% endfor %}

within the javascript onChange function but I'm not sure how to actually do this.

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.