title: Django - after submitting invalid form submit button upon click redirects
body: <p>I have a django project in which i have a form in a div being loaded by ajax.</p>
  
  <p>when I submit the form with empty fields it returns the form with the required fields shown. </p>
  
  <p>when I hit submit again it redirects to the action of the form instead of reloading the form in the div and showing errors as it does the first time I submit.</p>
  
  <p>does anyone have any idea where the error might be occurring? I imagine somewhere in the ajax or view in my django project.</p>
  
  <p>here is what is returned by the second submit:</p>
  
  <pre><code>{"success": false, "form": "&lt;head&gt;\n\n&lt;/head&gt;\n&lt;body&gt;\n&lt;form action=\"/cookbook/createrecipe/\" method=\"POST\" name=\"recipeform\" id=\"createrecipeform\"&gt;\n\t&lt;table&gt;\n\t\t&lt;div style='display:none'&gt;&lt;input type='hidden' name='csrfmiddlewaretoken' value='c5ea952ee2144b377b375d91b0843c75' /&gt;&lt;/div&gt;\n\t\t&lt;tr&gt;&lt;th&gt;&lt;label for=\"id_name\"&gt;Name:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;ul class=\"errorlist\"&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;input id=\"id_name\" type=\"text\" name=\"name\" maxlength=\"200\" /&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;th&gt;&lt;label for=\"id_author\"&gt;Author:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;ul class=\"errorlist\"&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;input id=\"id_author\" type=\"text\" name=\"author\" maxlength=\"100\" /&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;th&gt;&lt;label for=\"id_picture\"&gt;Picture:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input type=\"file\" name=\"picture\" id=\"id_picture\" /&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;th&gt;&lt;label for=\"id_ingredients\"&gt;Ingredients:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;ul class=\"errorlist\"&gt;&lt;li&gt;This field cannot be null.&lt;/li&gt;&lt;/ul&gt;&lt;textarea id=\"id_ingredients\" rows=\"10\" cols=\"40\" name=\"ingredients\"&gt;&lt;/textarea&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;th&gt;&lt;label for=\"id_steps\"&gt;Steps:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;ul class=\"errorlist\"&gt;&lt;li&gt;This field cannot be null.&lt;/li&gt;&lt;/ul&gt;&lt;textarea id=\"id_steps\" rows=\"10\" cols=\"40\" name=\"steps\"&gt;&lt;/textarea&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;th&gt;&lt;label for=\"id_prep_time\"&gt;Prep time:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;ul class=\"errorlist\"&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;input type=\"text\" name=\"prep_time\" id=\"id_prep_time\" /&gt;&lt;/td&gt;&lt;/tr&gt;\n&lt;tr&gt;&lt;th&gt;&lt;label for=\"id_type\"&gt;Type:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;ul class=\"errorlist\"&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;select name=\"type\" id=\"id_type\"&gt;\n&lt;option value=\"\" selected=\"selected\"&gt;---------&lt;/option&gt;\n&lt;option value=\"SW\"&gt;Sandwich&lt;/option&gt;\n&lt;option value=\"AP\"&gt;Appetizers&lt;/option&gt;\n&lt;option value=\"SD\"&gt;Sauces and Dressings&lt;/option&gt;\n&lt;option value=\"SS\"&gt;Soups and Salads&lt;/option&gt;\n&lt;option value=\"VG\"&gt;Vegetables&lt;/option&gt;\n&lt;option value=\"RG\"&gt;Rice, Grains and Beans&lt;/option&gt;\n&lt;option value=\"PA\"&gt;Pasta&lt;/option&gt;\n&lt;option value=\"BR\"&gt;Breakfast&lt;/option&gt;\n&lt;option value=\"MT\"&gt;Meat&lt;/option&gt;\n&lt;option value=\"SF\"&gt;Seafood&lt;/option&gt;\n&lt;option value=\"BP\"&gt;Bread and Pizza&lt;/option&gt;\n&lt;option value=\"DT\"&gt;Desserts&lt;/option&gt;\n&lt;/select&gt;&lt;input type=\"hidden\" name=\"reset_recipe\" id=\"id_reset_recipe\" /&gt;&lt;/td&gt;&lt;/tr&gt;\n\t&lt;/table&gt;\n\t&lt;p&gt;&lt;input type=\"submit\" value=\"Submit\"&gt;&lt;/p&gt;\n&lt;/form&gt;\n&lt;/body&gt;"}
  </code></pre>
  
  <p>here is my ajax code:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt; 
  $(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;
      });
  });
  &lt;/script&gt; 
  </code></pre>
  
  <p>here is the view: (createrecipe is the action of the form and account is the page that is loading the ajax)</p>
  
  <pre><code>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))
  </code></pre>
  
  <p>here is the create_form.html template:</p>
  
  <pre><code>&lt;head&gt;
  
  &lt;/head&gt;
  &lt;body&gt;
  &lt;form action="{% url cookbook.views.createrecipe %}" method="POST" name="recipeform" id="createrecipeform"&gt;
      &lt;table&gt;
          {% csrf_token %}
          {{ form.as_table }}
      &lt;/table&gt;
      &lt;p&gt;&lt;input type="submit" value="Submit"&gt;&lt;/p&gt;
  &lt;/form&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>and here is the account template that includes the create_form template:</p>
  
  <pre><code>{% extends "cookbook/base.html" %}
  {% load pagination_tags %}
  {% load comments %}
  
  
      &lt;h1&gt;{{ user }}'s Cookbook&lt;/h1&gt;
  
  &lt;ul&gt;
  {% block nav-cookbooks %}
  &lt;li&gt;&lt;a class="nav-inactive" href="/cookbooks/"&gt;Cookbooks&lt;/a&gt;&lt;/li&gt;
  {% endblock %}
  {% block nav-account %}
  &lt;li&gt;&lt;a class="nav-active" href="/account/"&gt;My Cookbook&lt;/a&gt;&lt;/li&gt;
  {% endblock %}
  &lt;/ul&gt;
  {% block content %}
  {% autopaginate recipe_list 6 %}
      &lt;div id="recipe_cont"&gt;
              {% for recipe in recipe_list %}
          &lt;div class="recipe"&gt;
              &lt;div class="button"&gt;    
              &lt;a href="{% url cookbook.views.userrecipe recipe.id %}" style="display: none;"&gt;&lt;/a&gt;   
              &lt;img src="{{ STATIC_URL }}chicknbraw.jpg" alt="" height="70" width="70" style="display:inline;" /&gt;
              &lt;h4&gt;{{ recipe.name }}&lt;/h4&gt;
               &lt;/div&gt;
              &lt;h5&gt;{{ recipe.author }}&lt;/h5&gt;
              &lt;h5&gt;Prep Time: {{ recipe.prep_time }} minutes&lt;/h5&gt;
  
              &lt;h6&gt;&lt;a href="/addrecipe/{{ recipe.id }}"&gt;Add Recipe&lt;/a&gt;
                  &lt;a href="/removerecipe/{{ recipe.id }}"&gt;Remove Recipe&lt;/a&gt;&lt;/h6&gt;
          &lt;/div&gt;
      {% endfor %}
      &lt;/div&gt;
  
      &lt;div id="popupContact" class="popup"&gt;
              &lt;a id="popupContactClose" style="cursor:pointer;float:right;"&gt;x&lt;/a&gt;
              &lt;p id="contactArea"&gt;
              &lt;h1 style="text-align:center"&gt;Create New Recipe&lt;/h1&gt;
              {% include 'cookbook/create_form.html' %} 
              &lt;/p&gt;
      &lt;/div&gt;
      &lt;div id="backgroundPopup"&gt;
      &lt;/div&gt;  
      &lt;div id="col2-footer"&gt;
      {% paginate %}
      &lt;p id="recipe_order_text"&gt; order by: &lt;a href="/userbook/ordered/name"&gt;abc&lt;/a&gt;|&lt;a href="/userbook/ordered/date"&gt;date&lt;/a&gt; 
      &lt;/div&gt;
  
  {% endblock %}
  
  {% block footer %}
          &lt;a class="create" style="cursor:pointer" &gt;Create New Recipe&lt;/a&gt;
  {% endblock %}
  </code></pre>
  
  <p>sorry for putting so much code but it all seems to rely upon another piece of code so I figured all relevant code would be helpful</p>
  
  <p>thanks for any help you can give me</p>
  
  <p>katie</p>