title: Submitting a Django Form in a Bootstrap Modal
body: <p>I am new to Django and I am trying to figure out how to submit a form inside of a modal. I have two Django apps in question, frontend and login. The frontend app delivers the page, and the login is supposed to process the form. I am using crispy forms to render the forms but cannot get the forms to submit. Been struggling with this for a few days. Read through many posts on this and still can't figure it out. Any help will greatly be appreciated. Thank you so much. I'm using Django version 1.6</p>
  <p>frontend app's urls.py:</p>
  <pre><code>from django.conf.urls import patterns, url
  from django.contrib import admin
  from frontend import views
  from login.views import registration
  
  urlpatterns = patterns('',
      url(r'^$', views.index, name='index'),
      url(r'^about/$', views.about, name='about'),
      url(r'^contact/$', views.contact, name='contact'),
      url(r'^$', 'index', name='index'),
      url(r'^$',views.registration, name='register'),
  )
  </code></pre>
  <p>frontend app's views.py:</p>
  <pre><code>from django.template import RequestContext
  from django.shortcuts import render_to_response
  from login.forms import RegistrationForm
  from login.forms import LoginForm
  from login.views import registration
  
  def index(request):
      return render_to_response('index.html', {'regform':RegistrationForm(),'loginform': LoginForm()} )
  
  
  def about(request):
      return render_to_response('about.html')
  
  def contact(request):
      return render_to_response('contact.html')
  </code></pre>
  <p>login apps's urls.py:</p>
  <pre><code>from django.conf.urls import patterns, url
  from login import views
  
  urlpatterns = patterns('',
     url(r'^register/$', views.registration, name='index.html')
  
  )
  </code></pre>
  <p>login app's views.py:</p>
  <pre><code>from django.template import RequestContext
  from django.shortcuts import render_to_response
  from login.forms import RegistrationForm
  
  
  
  def registration(request):
  
  
      context = RequestContext(request)
  
  
      registered = False
  
  
  if request.method == 'POST':
      
      user_form = RegistrationForm(request.POST)
      
  
      
      user = user_form.save()
  
          
      user.set_password(user.password)
      user.save()
  
      registered = True
  
     
  
  
  else:
      user_form = RegistrationForm()
      
  return render_to_response('index.html', {'regform': user_form}, context)
  
  def login(request):
     context = RequestContext(request)
     login_form = LoginForm()
     return render_to_response('index.html', {loginform: login_form}, context)
  </code></pre>
  <p>login app's forms.py:</p>
  <pre><code>from django.contrib.auth.models import User
  from django import forms
  from crispy_forms.helper import FormHelper
  from crispy_forms.layout import Submit, Layout, Field
  from crispy_forms.bootstrap import (PrependedText, PrependedAppendedText, FormActions)
  from login.models import User
  
  
  
  class RegistrationForm(forms.ModelForm):
       password = forms.CharField(widget=forms.PasswordInput())
  
       class Meta:
             model = User
             fields = ('username', 'email', 'first_name','last_name','password')
             helper = FormHelper()
             helper.form_method = 'POST'
             helper.add_input(Submit('save', 'save', css_class='btn-primary'))
  
       class LoginForm(forms.ModelForm):
             password = forms.CharField(widget=forms.PasswordInput())
  
   class Meta:
      model = User
      fields = ('username', 'password')
  @property   
  def helper(self):        
      helper = FormHelper()
          helper.form_method = 'POST'
          helper.add_input(Submit('save', 'save', css_class='btn-primary'))
      return helper
  </code></pre>
  <p>Index.html modal:</p>
  <pre><code>&lt;div class=&quot;modal fade&quot; id=&quot;myModal&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot;  aria-labelledby=&quot;myModalLabel&quot; aria-hidden=&quot;true&quot;&gt;
    &lt;div class=&quot;modal-dialog&quot;&gt;
      &lt;div class=&quot;modal-content&quot;&gt;
        &lt;div class=&quot;modal-header&quot;&gt;
          &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/button&gt;
          &lt;h4 class=&quot;modal-title&quot; id=&quot;myModalLabel&quot;&gt;Register &lt;/h4&gt;
        &lt;/div&gt;
        &lt;div class=&quot;modal-body&quot;&gt;
     &lt;ul class=&quot;nav nav-tabs&quot;&gt;
       &lt;li class=&quot;active&quot;&gt;&lt;a href=&quot;#tab1&quot; data-toggle=&quot;tab&quot;&gt;Login&lt;/a&gt;&lt;/li&gt;
           &lt;li&gt;&lt;a href=&quot;#tab2&quot; data-toggle=&quot;tab&quot;&gt;Register&lt;/a&gt;&lt;/li&gt;
       &lt;/ul&gt;
          &lt;form action=&quot;&quot; method=post&quot;&gt; 
           &lt;div class=&quot;tab-content&quot;&gt;
             &lt;div class=&quot;tab-pane active&quot; id=&quot;tab1&quot;&gt;
              
      {% crispy loginform %}
      
             &lt;/div&gt;
             &lt;div class=&quot;tab-pane&quot; id=&quot;tab2&quot;&gt;
               
      {% crispy regform %}
       
             &lt;/div&gt;
           &lt;/form&gt;
           &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=&quot;modal-footer&quot;&gt;
          &lt;button type=&quot;button&quot; class=&quot;btn btn-default&quot; data-dismiss=&quot;modal&quot;&gt;Cancel&lt;/button&gt;
          &lt;button type=&quot;button&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;
        
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  <p>Modal with Ajax attempt(snip):</p>
  <pre><code>&lt;div class=&quot;modal-footer&quot;&gt;
          &lt;button type=&quot;button&quot; class=&quot;btn btn-default&quot; data-dismiss=&quot;modal&quot;&gt;Cancel&lt;/button&gt;
          &lt;button id=&quot;register&quot; type=&quot;button&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;
          &lt;script&gt;
      $('#register').click(function(){
               console.log('am i called');
  
          $.ajax({
              type: &quot;POST&quot;,
              url: &quot;/register/&quot;,
              dataType: &quot;json&quot;,
              data: $(&quot;#login&quot;).serialize(),
              success: function(data) {
              alert(data.message);
          }
      });
  
  });
      &lt;/script&gt;
  </code></pre>
  <p>Login view for Ajax request:</p>
  <pre><code>def addUser(request):
  if request.is_ajax() and request.POST:
      data = {request.POST.get('item')}
      return HttpResponse(json.dumps(data), content_type='application/json') 
  else:
  raise Http404
  </code></pre>
  <p>As Requested Rendered HTML For Modal:</p>
  <pre><code>&lt;!-- Modal --&gt; 
  &lt;div class=&quot;modal fade&quot; id=&quot;myModal&quot; tabindex=&quot;-1&quot; role=&quot;dialog&quot;   aria-labelledby=&quot;myModalLabel&quot; aria-hidden=&quot;true&quot;&gt;
    &lt;div class=&quot;modal-dialog&quot;&gt;
      &lt;div class=&quot;modal-content&quot;&gt;
        &lt;div class=&quot;modal-header&quot;&gt;
          &lt;button type=&quot;button&quot; class=&quot;close&quot; data-dismiss=&quot;modal&quot; aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/button&gt;
          &lt;h4 class=&quot;modal-title&quot; id=&quot;myModalLabel&quot;&gt;Register &lt;/h4&gt;
        &lt;/div&gt;
        &lt;div class=&quot;modal-body&quot;&gt;
     &lt;ul class=&quot;nav nav-tabs&quot;&gt;
       &lt;li class=&quot;active&quot;&gt;&lt;a href=&quot;#tab1&quot; data-toggle=&quot;tab&quot;&gt;Login&lt;/a&gt;&lt;/li&gt;
           &lt;li&gt;&lt;a href=&quot;#tab2&quot; data-toggle=&quot;tab&quot;&gt;Register&lt;/a&gt;&lt;/li&gt;
       &lt;/ul&gt;
          &lt;form id=&quot;login&quot; action=&quot;/frontend/register/&quot; method=&quot;POST&quot;&gt; 
           &lt;div class=&quot;tab-content&quot;&gt;
             &lt;div class=&quot;tab-pane active&quot; id=&quot;tab1&quot;&gt;
              
      
  </code></pre>
  
                  Username* Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters</p>  
                  Password* 
  <pre><code>           &lt;/div&gt;
      
          
             &lt;div class=&quot;tab-pane&quot; id=&quot;tab2&quot;&gt;
               
      
  </code></pre>
  
                   Username*            Required. 30 characters or fewer. Letters, numbers and @/./+/-/_  characters</p>  
                  Email address
               
                  First name
                 
                  Last name
                 
                  Password* 
  <pre><code>           &lt;/div&gt;
           &lt;/form&gt;
           &lt;/div&gt;
        &lt;/div&gt;
      &lt;div class=&quot;modal-footer&quot;&gt; 
          &lt;button type=&quot;button&quot; class=&quot;btn btn-default&quot;   data-dismiss=&quot;modal&quot;&gt;Cancel&lt;/button&gt;
          &lt;button id=&quot;register&quot; type=&quot;button&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;
          &lt;script&gt;
      $('#register').click(function(){
               console.log('am i called');
  
          $.ajax({
              type: &quot;POST&quot;,
              url: &quot;/register/&quot;,
              
              data: $(regform).serialize(),
              success: function(data) {
                  if (!(data['success'])) {
          
                      $(example_form).replaceWith(data['form_html']);
              }
              else {
          
                 $(example_form).find('.success-message').show();
              }
              },
           error: function () {
              $(example_form).find('.error-message').show()
              }
               }
              });
  
              });
      &lt;/script&gt;
          
  
       &lt;/div&gt; 
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  <p>Update Ajax:</p>
  <pre><code>&lt;script&gt;
  $(document).ready(function() {
  var frm = $('#id-registration');
   frm.submit(function (e) {
  
  
      $.ajax({
          type: frm.attr('method'), &lt;!-- Get the form's method attribute(defined in login/forms.py --&gt;
          url: frm.attr('action'),  &lt;!-- Get the form's action attribute(defined in login/forms.py --&gt;
          data: $(frm).serialize(),    &lt;!-- package the data --&gt;
          success: function (data) {        &lt;!-- if success return message --&gt;
             if (!(data['success'])) {
              console.log('ifcalled')
              $(frm).replaceWith(data['form_html']); &lt;!-- send replacement form with errors --&gt;
             }
             else{
               console.log('elseCalled')
               $(&quot;#div-form&quot;).html(&quot;Thanks!&quot;);
              // $(frm).find('.success-message').show();
              }
          },
          error: function(data) {           &lt;!-- else print error --&gt;
              $(frm).find('.error-message').show()
          }
      });
    e.preventDefault(); &lt;!-- problem is here, validation is all ways false --&gt;
  
  });
  
  });
  &lt;/script&gt;
  </code></pre>
  <p>Update:
  The form is now being submitted to the database. However form Validation is not functioning. The if/else control seems to always validate false. If I remove form.submit(). It functions and shows form errors, but the page refreshes.</p>
  <p>updated views.py:</p>
  <pre><code>def addUser(request):
  
  form = RegistrationForm(data=request.POST or None)
  if form.is_valid():
      # You could actually save through AJAX and return a success code here
      form.save()
      return {'success': True}
  
  form_html = render_crispy_form(form)
  return {'success': False, 'form_html': form_html}
  </code></pre>
  <p>updated Forms.py:</p>
  <pre><code>class RegistrationForm(forms.ModelForm):
      password = forms.CharField(widget=forms.PasswordInput())
      class Meta:
           model = User
           fields = ('username', 'email', 'first_name','last_name','password')
      def __init__(self, *args, **kwargs):
               super(RegistrationForm, self).__init__(*args, **kwargs)
               self.helper = FormHelper()
               self.helper.form_id = 'id-registration'
               self.helper.form_class = 'blueForms'
               self.helper.form_method = 'post'
               self.helper.form_action = '/register/'
               self.helper.add_input(Submit('submit', 'Submit'))
  </code></pre>
  <p>The Problem has been resolved:</p>
  <pre><code>&lt;script type=&quot;text/javascript&quot;     src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;{% static 'js/jquery-validation- 1.11.1/jquery.validate.js' %}&quot;&gt;&lt;/script&gt;   
  &lt;script&gt;
  $(document).ready(function () {
    var frm = $('#id-registration');
    $('#id-registration').validate({
    
      rules: {
          username: {required: true},
          email: {required: true},
          password: {required: true}
          
  },
  
   submitHandler: function(){
      $.ajax({//begin
          type: 'POST', &lt;!-- Get the form's method attribute(defined in login/forms.py --&gt;
          url: frm.attr('action'),  &lt;!-- Get the form's action attribute(defined in   login/forms.py --&gt;
          data: $(frm).serialize(),    &lt;!-- package the data --&gt;
          success: function(data){
              $(frm).hide();
      $(&quot;#div-form&quot;).html(&quot;&lt;h3 style='text-align:center;'&gt;Thank you, for Registering!&lt;/h3&gt;&quot;);
      
          },
          error: function(data) {           &lt;!-- else print error --&gt;
              $(&quot;#div-form&quot;).html(&quot;Failure!&quot;);
          }//end error
      });//end ajax
  
      return false;
      }   
      });   
      });
  
  
  
      &lt;/script&gt;
  </code></pre>