在Bootstrap模式中提交Django表单

时间:2014-03-23 18:14:55

标签: jquery python django forms twitter-bootstrap

嘿伙计我是Django的新手,我正在试图找出如何在模态中提交表单。我有两个有问题的Django应用程序,前端和登录。前端应用程序提供页面,登录应该处理表单。我使用crispy表单来呈现表单但无法提交表单。几天来一直在努力奋斗。阅读了很多关于此的帖子,仍然无法弄清楚。任何帮助将不胜感激。非常感谢。我使用的是Django 1.6版

前端app的urls.py:

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'),
)

前端app的views.py:

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')

登录应用程序的urls.py:

from django.conf.urls import patterns, url
from login import views

urlpatterns = patterns('',
   url(r'^register/$', views.registration, name='index.html')

)

登录app的views.py:

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)

登录app的forms.py:

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

Index.html模式:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog"  aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Register </h4>
      </div>
      <div class="modal-body">
   <ul class="nav nav-tabs">
     <li class="active"><a href="#tab1" data-toggle="tab">Login</a></li>
         <li><a href="#tab2" data-toggle="tab">Register</a></li>
     </ul>
        <form action="" method=post"> 
         <div class="tab-content">
           <div class="tab-pane active" id="tab1">

    {% crispy loginform %}

           </div>
           <div class="tab-pane" id="tab2">

    {% crispy regform %}

           </div>
         </form>
         </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary">Submit</button>

      </div>
    </div>
  </div>
</div>

使用Ajax尝试的模式(剪辑):

<div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button id="register" type="button" class="btn btn-primary">Submit</button>
        <script>
    $('#register').click(function(){
             console.log('am i called');

        $.ajax({
            type: "POST",
            url: "/register/",
            dataType: "json",
            data: $("#login").serialize(),
            success: function(data) {
            alert(data.message);
        }
    });

});
    </script>

Ajax请求的登录视图:

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

如要求的模式渲染HTML:

<!-- Modal --> 
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"   aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Register </h4>
      </div>
      <div class="modal-body">
   <ul class="nav nav-tabs">
     <li class="active"><a href="#tab1" data-toggle="tab">Login</a></li>
         <li><a href="#tab2" data-toggle="tab">Register</a></li>
     </ul>
        <form id="login" action="/frontend/register/" method="POST"> 
         <div class="tab-content">
           <div class="tab-pane active" id="tab1">
                用户名*必填。 30个字符或更少。字母,数字和@ / ./ + / - / _字符

                密码*
           </div>


           <div class="tab-pane" id="tab2">
                 用户名*必填。 30个字符或更少。字母,数字和@ / ./ + / - / _字符

                电子邮件地址                               名字                                 姓                                 密码*
           </div>
         </form>
         </div>
      </div>
    <div class="modal-footer"> 
        <button type="button" class="btn btn-default"   data-dismiss="modal">Cancel</button>
        <button id="register" type="button" class="btn btn-primary">Submit</button>
        <script>
    $('#register').click(function(){
             console.log('am i called');

        $.ajax({
            type: "POST",
            url: "/register/",

            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()
            }
             }
            });

            });
    </script>


     </div> 
    </div>
  </div>
</div>

更新Ajax:

<script>
$(document).ready(function() {
var frm = $('#id-registration');
 frm.submit(function (e) {


    $.ajax({
        type: frm.attr('method'), <!-- Get the form's method attribute(defined in login/forms.py -->
        url: frm.attr('action'),  <!-- Get the form's action attribute(defined in login/forms.py -->
        data: $(frm).serialize(),    <!-- package the data -->
        success: function (data) {        <!-- if success return message -->
           if (!(data['success'])) {
            console.log('ifcalled')
            $(frm).replaceWith(data['form_html']); <!-- send replacement form with errors -->
           }
           else{
             console.log('elseCalled')
             $("#div-form").html("Thanks!");
            // $(frm).find('.success-message').show();
            }
        },
        error: function(data) {           <!-- else print error -->
            $(frm).find('.error-message').show()
        }
    });
  e.preventDefault(); <!-- problem is here, validation is all ways false -->

});

});
</script>

更新: 表单现在正在提交给数据库。但是表单验证不起作用。 if / else控件似乎总是验证false。如果我删除form.submit()。它起作用并显示表单错误,但页面刷新。

更新了views.py:

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}

更新了Forms.py:

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'))

问题已经解决:

<script type="text/javascript"     src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript" src="{% static 'js/jquery-validation- 1.11.1/jquery.validate.js' %}"></script>   
<script>
$(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', <!-- Get the form's method attribute(defined in login/forms.py -->
        url: frm.attr('action'),  <!-- Get the form's action attribute(defined in   login/forms.py -->
        data: $(frm).serialize(),    <!-- package the data -->
        success: function(data){
            $(frm).hide();
    $("#div-form").html("<h3 style='text-align:center;'>Thank you, for Registering!</h3>");

        },
        error: function(data) {           <!-- else print error -->
            $("#div-form").html("Failure!");
        }//end error
    });//end ajax

    return false;
    }   
    });   
    });



    </script>

3 个答案:

答案 0 :(得分:1)

首先,我会启动您的浏览器开发者工具(例如Firefox中的Firebug)。如果发送了POST请求,请在“网络”选项卡中密切监视。

发送请求后,您可以检查请求的内容和答案。这有助于确定您的表单是否捕获了输入中的所有数据,或者您的urls.py可能有问题。

如果表单提交正确(状态200),您可以开始调试Django App。

答案 1 :(得分:0)

您有两种可能性:

  1. 通过HTML帖子请求
  2. <button>放入<form>。将提交按钮的类型更改为type="submit"并通过添加操作并修复方法中的拼写错误来修复表单属性。

    1. 通过AJAX请求。
    2. 在提交按钮中添加一个id,并将click事件附加到执行AJAX请求的按钮上。

      <script>
          $('#login').on('click', function (e) {
              // login action
          });
      </script>
      

      有关详细信息,请阅读http://getbootstrap.com/javascript/#modals-examples

答案 2 :(得分:0)

我有一个类似的问题,摆脱data-dismiss="modal"为我修复它。

它没有回答你的问题,但是有相同问题的人最终会出现在这个页面上,也许这会对他们有所帮助。