Eimantas
Eimantas

Reputation: 429

Using Jquery in Django model formsets

This is actually a Jquery question. My web application requires to zip two formsets. I have successfully zipped them, but I am not sure how should I submit the form using Jquery and Ajax (the user clicks the form and formsets are saved without reloading the page). I know that I have to "catch" the formset submit event using Jquery and then use Jquery.ajax(), but I am not sure how to "catch" the event when the user clicks "submit" button under the form, because the forms are generated automatically in Django and therefore I can not use form's ID in Jquery code.

This is my views. The code works perfectly now:

def App(request):
lectures = Lecture.objects.all()
TopicFormSet = modelformset_factory(Topic, extra=0)
SummaryFormSet = modelformset_factory(Summary, extra=0)
t_formset = TopicFormSet()
s_formset = SummaryFormSet()
# zipping the formsets
zipped = zip(t_formset.forms, s_formset.forms) 
#saving formsets:
if request.method == 'POST':
    t_formset = TopicFormSet(request.POST)
    s_formset = SummaryFormSet(request.POST)
    if t_formset.is_valid() and s_formset.is_valid():
        t_formset.save() and s_formset.save()
        zipped = zip(t_formset.forms, s_formset.forms)
    else:
        return HttpResponse("not valid, dude") # for testing purposes
return render (request, "app.html", {"lectures" : lectures, "zipped" : zipped, "t_formset" : t_formset, "s_formset" : s_formset})

My templates:

<form action = "http://127.0.0.1:8000/app/" method = "POST">
        {% csrf_token %}
        <!-- t_formset.management_form -->
        {{ t_formset.management_form }}
        <!-- t_formset.management_form -->
        {{ s_formset.management_form }}
        <!-- formsets -->
        {% for topic, summary in zipped %}
        <div id="topic">{{ topic }}</div>
        <br>
        <input type="submit" value="Submit" id="mygt" />
        <br>
        <div id="summary">{{ summary }}</div>
        <br>
        <input type="submit" value="Submit" id="mygt" />
        {% endfor %}

Upvotes: 0

Views: 228

Answers (2)

Ishafizan Ishak
Ishafizan Ishak

Reputation: 31

have a look at django-dajax and django-dajaxice for super-easy to use ajax libraries: examples: http://www.dajaxproject.com/dajaxice/ http://www.dajaxproject.com/multiply/

Upvotes: 1

user2213551
user2213551

Reputation: 26

$(document).ready(function()
    $(#mygt).click(function() 
         $.post or $.ajax

Those should start you out.

Upvotes: 0

Related Questions