2012-05-08 69 views
1

我有一個django項目,其中我有一個窗體在由ajax加載的div中。Django - 在點擊重定向後提交無效表單提交按鈕

當我提交帶空字段的表單時,它將返回帶有顯示的必填字段的表單。

當我再次提交時,它重定向到表單的操作,而不是重新加載div中的表單,並顯示錯誤,因爲它是第一次提交。

沒有人有任何想法可能發生錯誤的地方嗎?我想象在我的Django項目中的某個地方。

這裏是由第二返回提交:

{"success": false, "form": "<head>\n\n</head>\n<body>\n<form action=\"/cookbook/createrecipe/\" method=\"POST\" name=\"recipeform\" id=\"createrecipeform\">\n\t<table>\n\t\t<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='c5ea952ee2144b377b375d91b0843c75' /></div>\n\t\t<tr><th><label for=\"id_name\">Name:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_name\" type=\"text\" name=\"name\" maxlength=\"200\" /></td></tr>\n<tr><th><label for=\"id_author\">Author:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input id=\"id_author\" type=\"text\" name=\"author\" maxlength=\"100\" /></td></tr>\n<tr><th><label for=\"id_picture\">Picture:</label></th><td><input type=\"file\" name=\"picture\" id=\"id_picture\" /></td></tr>\n<tr><th><label for=\"id_ingredients\">Ingredients:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_ingredients\" rows=\"10\" cols=\"40\" name=\"ingredients\"></textarea></td></tr>\n<tr><th><label for=\"id_steps\">Steps:</label></th><td><ul class=\"errorlist\"><li>This field cannot be null.</li></ul><textarea id=\"id_steps\" rows=\"10\" cols=\"40\" name=\"steps\"></textarea></td></tr>\n<tr><th><label for=\"id_prep_time\">Prep time:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><input type=\"text\" name=\"prep_time\" id=\"id_prep_time\" /></td></tr>\n<tr><th><label for=\"id_type\">Type:</label></th><td><ul class=\"errorlist\"><li>This field is required.</li></ul><select name=\"type\" id=\"id_type\">\n<option value=\"\" selected=\"selected\">---------</option>\n<option value=\"SW\">Sandwich</option>\n<option value=\"AP\">Appetizers</option>\n<option value=\"SD\">Sauces and Dressings</option>\n<option value=\"SS\">Soups and Salads</option>\n<option value=\"VG\">Vegetables</option>\n<option value=\"RG\">Rice, Grains and Beans</option>\n<option value=\"PA\">Pasta</option>\n<option value=\"BR\">Breakfast</option>\n<option value=\"MT\">Meat</option>\n<option value=\"SF\">Seafood</option>\n<option value=\"BP\">Bread and Pizza</option>\n<option value=\"DT\">Desserts</option>\n</select><input type=\"hidden\" name=\"reset_recipe\" id=\"id_reset_recipe\" /></td></tr>\n\t</table>\n\t<p><input type=\"submit\" value=\"Submit\"></p>\n</form>\n</body>"} 

這裏是我的Ajax代碼:

<script type="text/javascript"> 
$(document).ready(function(){ 
    var form = $('form#createrecipeform'); 
    form.submit(function(e) { 
    e.preventDefault(); 
    console.log('ajax form submission function called successfully.'); 
    //form = $(this); 
    console.log(form) 
    var serialized_form = form.serialize(); 
     $.ajax({ type: "POST",  
      url: $(this).attr('action'), 
      data: serialized_form,  
      success: (function(data) {  
       console.log('ajax success function called successfully.'); 
       data = $.parseJSON(data); 
       if (data.success) { 
        console.log('success'); 
       } else {   
        console.log('failure'); 
        var newForm = data.form; 
        form.replaceWith(newForm); 
       } 
      }) 
     }); 
     return false; 
    }); 
}); 
</script> 

這裏的觀點:(createrecipe的形式和帳戶的動作加載ajax的頁面)

def createrecipe(request): 
     print "entering createrecipeview" 
     if request.method == 'POST': 
      print "form is a post" 
      form = RecipeForm(request.POST) 
      print form.errors 
      if form.is_valid(): 
       print "form is valid" 
       form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]}) 
       form = form.save() 

       t = loader.get_template('cookbook/create_form.html') 
       c = RequestContext(request, { 
       'form': form, 
       }) 

       data = { 
       'replace': True, 
       'form': t.render(c), 
       'success': True, 
       } 

       json = simplejson.dumps(data) 
       return HttpResponse(json, mimetype='text/plain') 
      else: 
       print "form is invalid" 
       form = RecipeForm(request.POST) 
       t = loader.get_template('cookbook/create_form.html') 
       c = RequestContext(request, { 
        'form':form, 
       }) 

       data ={ 
        'form': t.render(c), 
        'success': False, 
       } 

       json = simplejson.dumps(data) 
       return HttpResponse(json, mimetype='text/plain') 

def account(request): 
    user = request.user 
    if request.user.is_authenticated(): 

     cookbooks = user.cookbooks 
     if cookbooks.all().exists(): 
      cookbook = cookbooks.all()[0] 
      form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]}) 
      recipe_list = cookbook.recipes.all() 
     else: 
      raise Http404 
    else: 
     return HttpResponseRedirect('/accounts/login') 
    t = loader.get_template('cookbook/account.html') 
    c = RequestContext(request, { 
     'form': form, 
     'recipe_list': recipe_list 
    }) 
    return HttpResponse(t.render(c)) 

這裏是create_form.html模板:

<head> 

</head> 
<body> 
<form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform"> 
    <table> 
     {% csrf_token %} 
     {{ form.as_table }} 
    </table> 
    <p><input type="submit" value="Submit"></p> 
</form> 
</body> 

,這裏是帳號模板,其中包括create_form模板:

{% extends "cookbook/base.html" %} 
{% load pagination_tags %} 
{% load comments %} 


    <h1>{{ user }}'s Cookbook</h1> 

<ul> 
{% block nav-cookbooks %} 
<li><a class="nav-inactive" href="/cookbooks/">Cookbooks</a></li> 
{% endblock %} 
{% block nav-account %} 
<li><a class="nav-active" href="/account/">My Cookbook</a></li> 
{% endblock %} 
</ul> 
{% 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> 
      <img src="{{ STATIC_URL }}chicknbraw.jpg" alt="" height="70" width="70" style="display:inline;" /> 
      <h4>{{ recipe.name }}</h4> 
      </div> 
      <h5>{{ recipe.author }}</h5> 
      <h5>Prep Time: {{ recipe.prep_time }} minutes</h5> 

      <h6><a href="/addrecipe/{{ recipe.id }}">Add Recipe</a> 
       <a href="/removerecipe/{{ recipe.id }}">Remove Recipe</a></h6> 
     </div> 
    {% endfor %} 
    </div> 

    <div id="popupContact" class="popup"> 
      <a id="popupContactClose" style="cursor:pointer;float:right;">x</a> 
      <p id="contactArea"> 
      <h1 style="text-align:center">Create New Recipe</h1> 
      {% include 'cookbook/create_form.html' %} 
      </p> 
    </div> 
    <div id="backgroundPopup"> 
    </div> 
    <div id="col2-footer"> 
    {% paginate %} 
    <p id="recipe_order_text"> order by: <a href="/userbook/ordered/name">abc</a>|<a href="/userbook/ordered/date">date</a> 
    </div> 

{% endblock %} 

{% block footer %} 
     <a class="create" style="cursor:pointer" >Create New Recipe</a> 
{% endblock %} 

對不起,把這麼多的代碼,但是這一切似乎依賴於另一段代碼,所以我想所有相關的代碼會是有幫助的

感謝任何幫助,您可以給我

凱蒂

回答

0

在JavaScript中,您劫持表單以便通過ajax提交,但隨後您在表單上調用replaceWith,因此您的劫持表單將被刪除,並被替換爲新的未劫持表單。爲了解決這個問題,你既可以

1)僅替換形式的內容 - 這應該工作,因爲你只連接事件的形式本身,而不是它的子元素

2)撰寫您的JS作爲函數,您可以首先調用初始表單,然後再通過ajax加載任何新表單。

更新:例如,

<script type="text/javascript"> 
$(document).ready(function(){ 

    function hijack() { 
     var form = $('form#createrecipeform'); 
     form.submit(function(e) { 
      e.preventDefault(); 
      console.log('ajax form submission function called successfully.'); 
      //form = $(this); 
      console.log(form) 
      var serialized_form = form.serialize(); 
      $.ajax({ type: "POST", 
       url: $(this).attr('action'), 
       data: serialized_form, 
       success: (function(data) { 
        console.log('ajax success function called successfully.'); 
        data = $.parseJSON(data); 
        if (data.success) { 
         console.log('success'); 
        } else {   
         console.log('failure'); 
         var newForm = data.form; 
         form.replaceWith(newForm); 
         hijack(); 
        } 
       }) 
      }); 
      return false; 
     }); 
    }; 

    hijack(); 

}); 
</script> 
+0

其中JS我應該寫爲一個函數?你的意思是我在帖子頂部寫的整個js函數? –

+0

是的,只是form.submit(...)調用。把它放在一個函數中,然後立即調用它,並且在replaceWith()部分之後立即調用它。 – Greg

+0

但我的replaceWith()函數包含在我的form.submit()中。我怎麼稱呼它?對不起,如果我今天有點密集 - 我剛剛完成了決賽 –