gpt4 book ai didi

jquery - 在 Bootstrap 模式中提交 Django 表单

转载 作者:太空狗 更新时间:2023-10-30 01:34:13 25 4
gpt4 key购买 nike

我是 Django 的新手,我正在尝试弄清楚如何在模式内提交表单。我有两个有问题的 Django 应用程序,前端和登录。前端应用程序提供页面,登录应该处理表单。我正在使用脆皮表格来呈现表格,但无法提交表格。几天来一直在努力解决这个问题。看了很多关于这个的帖子,还是想不通。任何帮助将不胜感激。太感谢了。我正在使用 Django 1.6 版

前端应用的 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'),
)

前端应用的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')

)

登录应用的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)

登录应用程序的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 请求的登录 View :

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>

最佳答案

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

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

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

关于jquery - 在 Bootstrap 模式中提交 Django 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22594976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com