這實際上是一個jquery問題。我的web應用程序需要壓縮兩個formset。我已經成功壓縮了它們,但我不確定如何使用Jquery和Ajax提交表單(用戶單擊表單並保存表單而不重新加載頁面)。我知道我必須使用Jquery「捕捉」formset提交事件,然後使用Jquery.ajax(),但我不確定如何在用戶單擊表單下的「submit」按鈕時「捕捉」事件,因爲表單在Django中自動生成,因此我無法在Jquery代碼中使用表單的ID。在Django模型框架中使用jquery
這是我的看法。該代碼現在完美的作品:
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})
我的模板:
<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 %}