自從我開始使用jquery和ajax以來,我的django網站變得非常臃腫。 我是新來的ajax和JavaScript,所以請記住,當迴應和抱歉,如果我有點困惑。使用jquery加載一個形式的Django模板
基本上我有一個模板,有一個窗體來創建一個配方。我使用jquery .load將此模板加載到另一頁上的彈出式div。窗體似乎加載到div罰款,但當我嘗試提交表單,沒有任何反應(沒有驗證檢查或任何 - 如果我離開字段爲空它不會返回錯誤。)奇怪的是,當我訪問實際頁面我正在加載jquery,表單完美地工作。這已經使我陷入了很大的困境,我很樂意繼續前進,所以任何幫助都非常感謝。
這裏是負載腳本:
<script type="text/javascript">
$(document).ready(function(){
$(".create").on("click", function(){
$("#popupContact").load("/cookbook/createrecipe #createform");
});
});
</script>
模板頁面加載形式:
{% block content %}
{% autopaginate recipe_list 6 %}
<div id="recipe_cont">
{% for recipe in recipe_list %}
<div class="recipe">
<div class="button">
<a href="{% url cookbook.views.userrecipe recipe.id %}" style="display: none;"></a>
<h4>{{ recipe.name }}</h4>
<h5>{{ recipe.author }}</h5>
<h5>Prep Time: {{ recipe.prep_time }} minutes</h5>
</div>
</div>
{% endfor %}
</div>
<div id="popupContact" class="popup">
<a id="popupContactClose" style="cursor:pointer;float:right;">x</a>
<p id="contactArea"></p>
</div>
<div id="backgroundPopup">
</div>
<div id="col2-footer">
{% paginate %}
</div>
{% endblock %}
創建-配方模板:
{% extends "cookbook/base.html" %}
{% block content %}
<div id="createform">
<h1>Create New Recipe</h1>
<form action="." method="POST">
<table>
{% csrf_token %}
{{ form.as_table }}
</table>
<p><input type="submit" value="Submit"></p>
</form>
</div>
{% endblock %}
創建-配方視圖:
def createrecipe(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/index/')
else:
if request.method == 'POST':
print 1
form = RecipeForm(request.POST)
if form.is_valid():
print 2
recipe = form.save(commit=False)
recipe.original_cookbook = request.user.cookbooks.all()[0]
recipe.pub_date = datetime.datetime.now()
recipe.save()
user = request.user
cookbooks = user.cookbooks
cookbook = cookbooks.all()[0]
cookbook.recipes.add(recipe)
return HttpResponseRedirect('/account')
else:
form = RecipeForm()
return render_to_response('cookbook/createrecipe.html',
{'form':form},
context_instance=RequestContext(request))
的JavaScript jQuery的表單代碼:
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
var options ={
target: '#popupContact',
url: '{% url createrecipe %}',
success: function() {
alert("Thank you for your comment!");
}
};
$('#createrecipe').ajaxForm(options);
});
</script>
感謝, snackerfish
EDIT1:馬克指出,我的表單動作是錯誤的,這樣解決。
由於某種原因,當我改變。到{%url'createrecipe'%}表單不再加載到div中。但我認爲這是正確的答案,任何想法爲什麼它不會再加載? – snackerfish 2012-04-23 17:15:17
爲了將來的兼容性,引用url名稱的語法假定您正在使用'{%load url from future%}'。如果不是,你應該刪除引號。 – 2012-04-23 17:18:52
非常感謝你標記這正是問題:) – snackerfish 2012-04-23 17:20:03