在引导模式中提交 Django 表单
Posted
技术标签:
【中文标题】在引导模式中提交 Django 表单【英文标题】:Submitting a Django Form in a Bootstrap Modal 【发布时间】:2014-04-30 22:59:45 【问题描述】:我是 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">×</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">×</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 控件似乎总是验证为假。如果我删除 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>
【问题讨论】:
【参考方案1】:你有两种可能:
-
通过 HTML 发布请求
将<button>
放入<form>
。将提交按钮的类型更改为type="submit"
,并通过添加操作和修复方法中的拼写错误来修复表单属性。
-
通过 AJAX 请求。
向提交按钮添加一个 ID,并将一个点击事件附加到执行 AJAX 请求的按钮。
<script>
$('#login').on('click', function (e)
// login action
);
</script>
更多信息请阅读http://getbootstrap.com/javascript/#modals-examples
【讨论】:
感谢您的回复。我一直试图让 Ajax 工作,但我的 JS 没有达到标准。我在第一篇文章中将我尝试过的内容添加到代码库中。【参考方案2】:首先,我会启动您的浏览器开发工具(例如 Firefox 中的 Firebug)。如果您的 POST 请求已发送或未发送,请在 Network 选项卡中密切监视。
请求发送后,您可以检查请求的内容和答案。这有助于确定您的表单是否从输入中捕获了所有数据,或者您的 urls.py 是否有问题。
如果表单提交正确(状态 200),您可以开始调试您的 Django 应用程序。
【讨论】:
当我点击提交时,我没有看到任何事情发生。 然后看起来您的提交按钮未绑定到表单。你能发布呈现的 HTML 代码吗? 我把它贴出来了。抱歉,我无法将其标记为格式。谢谢。 在您的 ajax 请求中,您希望提交 id="login" 的表单数据。尝试数据: $("#login").serialize() 在 Debug Tools > Console 中检查错误消息 谢谢。我试了一下,还是没有。我什至没有收到按钮按下的 console.log("clicked") 调用。【参考方案3】:我遇到了类似的问题,摆脱了data-dismiss="modal"
为我解决了这个问题。
它不能回答你的问题,但有同样问题的人最终会出现在这个页面上,也许这会对他们有所帮助。
【讨论】:
以上是关于在引导模式中提交 Django 表单的主要内容,如果未能解决你的问题,请参考以下文章
在 Bootstrap Modal 中使用 django 清晰表单的 AJAX 反馈表单
如何在不刷新页面的情况下使用 django-crispy-forms 实现引导模式表单