- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个带有 3 个输入和步骤按钮的 html 表单。
views.py
中的输入一步一步地在用户按下任何按钮的任何时间,以及
在最后提交时没有一起 .
views.py
中尝试了此代码在 django 后端接受输入,但我在
views.py
中什么也没得到(如果我将按钮类型从
button
更改为
submit
然后我得到结果坚果刷新页面,我不能去第 2 步)
if request.method == 'POST' and 'first_step' in request.POST:
print '1'
firstname= request.POST.get('firstname')
if request.method == 'POST' and 'second_step' in request.POST:
print '2'
lastname= request.POST.get('lastname')
if request.method == 'POST' and 'final_step' in request.POST:
print '3'
email= request.POST.get('email')
这是我的 html 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form wizard with circular tabs</title>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<section>
<div class="wizard">
<div class="wizard-inner">
<div class="connecting-line"></div>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">
<a href="#step1" data-toggle="tab" aria-controls="step1" role="tab" title="Step 1">
<span class="round-tab">
<i class="glyphicon glyphicon-folder-open"></i>
</span>
</a>
</li>
<li role="presentation" class="disabled">
<a href="#step2" data-toggle="tab" aria-controls="step2" role="tab" title="Step 2">
<span class="round-tab">
<i class="glyphicon glyphicon-pencil"></i>
</span>
</a>
</li>
<li role="presentation" class="disabled">
<a href="#step3" data-toggle="tab" aria-controls="step3" role="tab" title="Step 3">
<span class="round-tab">
<i class="glyphicon glyphicon-picture"></i>
</span>
</a>
</li>
<li role="presentation" class="disabled">
<a href="#complete" data-toggle="tab" aria-controls="complete" role="tab" title="Complete">
<span class="round-tab">
<i class="glyphicon glyphicon-ok"></i>
</span>
</a>
</li>
</ul>
</div>
<form role="form">
<div class="tab-content">
<div class="tab-pane active" role="tabpanel" id="step1">
<div class="step1">
<div class="row">
<div class="col-md-6">
<label for="exampleInputEmail1">First Name</label>
<input type="email" name="firstname" class="form-control" id="exampleInputEmail1" placeholder="First Name">
</div>
</div>
</div>
<ul class="list-inline pull-right">
<li><button type="button" name="first_step" class="btn btn-primary next-step">Save and continue</button></li>
</ul>
</div>
<div class="tab-pane" role="tabpanel" id="step2">
<div class="step2">
<div class="step-22">
<label for="exampleInputEmail1">Last Name</label>
<input type="email" name="lastname" class="form-control" id="exampleInputEmail1" placeholder="Last Name">
</div>
</div>
<ul class="list-inline pull-right">
<li><button type="button" class="btn btn-default prev-step">Previous</button></li>
<li><button type="button" name="second_step" class="btn btn-primary next-step">Save and continue</button></li>
</ul>
</div>
<div class="tab-pane" role="tabpanel" id="step3">
<div class="step33">
<label for="exampleInputEmail1">email</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Last Name">
</div>
<ul class="list-inline pull-right">
<li><button type="button" class="btn btn-default prev-step">Previous</button></li>
<li><button type="button" name="final_step" class="btn btn-primary btn-info-full next-step">Save and continue</button></li>
</ul>
</div>
<div class="tab-pane" role="tabpanel" id="complete">
<div class="step44">
<h5>Completed</h5>
</div>
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</section>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
//Initialize tooltips
$('.nav-tabs > li a[title]').tooltip();
//Wizard
$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
var $target = $(e.target);
if ($target.parent().hasClass('disabled')) {
return false;
}
});
$(".next-step").click(function (e) {
var $active = $('.wizard .nav-tabs li.active');
$active.next().removeClass('disabled');
nextTab($active);
});
$(".prev-step").click(function (e) {
var $active = $('.wizard .nav-tabs li.active');
prevTab($active);
});
});
function nextTab(elem) {
$(elem).next().find('a[data-toggle="tab"]').click();
}
function prevTab(elem) {
$(elem).prev().find('a[data-toggle="tab"]').click();
}
//according menu
$(document).ready(function()
{
//Add Inactive Class To All Accordion Headers
$('.accordion-header').toggleClass('inactive-header');
//Set The Accordion Content Width
var contentwidth = $('.accordion-header').width();
$('.accordion-content').css({});
//Open The First Accordion Section When Page Loads
$('.accordion-header').first().toggleClass('active-header').toggleClass('inactive-header');
$('.accordion-content').first().slideDown().toggleClass('open-content');
// The Accordion Effect
$('.accordion-header').click(function () {
if($(this).is('.inactive-header')) {
$('.active-header').toggleClass('active-header').toggleClass('inactive-header').next().slideToggle().toggleClass('open-content');
$(this).toggleClass('active-header').toggleClass('inactive-header');
$(this).next().slideToggle().toggleClass('open-content');
}
else {
$(this).toggleClass('active-header').toggleClass('inactive-header');
$(this).next().slideToggle().toggleClass('open-content');
}
});
return false;
});
</script>
</body>
</html>
最佳答案
几个小时前我写了一个这个问题的答案,然后我删除了那个,因为我不得不意识到我只是部分地给出了这个问题的解决方案,因为这个问题比最初看起来要复杂一些。
正如 OP 所写:如果您使用 类型=“提交”按钮输入,输入会被提交,但同时页面会刷新和使用此表格 这不是目的。如果您使用 类型=“按钮”输入,则输入数据将不会到达服务器(仅当您将提交的数据收集到一个 javascript 对象中,然后启动 AJAX 调用并使用该 AJAX 请求将其发送到服务器时)。
它基本上也不是一个 Django 问题,而更像是一个 javascript/AJAX 调用问题。并且还调用了一些安全问题来解决。由于提交,您还必须以某种方式向服务器发送 CSRF token 。所以,它可以解决,这对任何人来说都需要一些时间。
关于这个主题的一个很好的来源在这里:
https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html (然而,这篇文章在某些方面,在这种特殊情况下没用)
这就是它的工作原理
很久以前 我没有使用过 Django 和 Python(现在更像是使用 PHP 和 Joomla),但我只是在 Python 3.7 上启动了一个 Django 2.1.3 以确保它正常工作(以下内容也应该在旧版本中工作,很少如果需要修改)
我创建了一个名为“myuserform”的应用程序,并首先创建了一个 型号 在 模型.py
模型.py
from django.db import models
from django.utils import timezone
class NewUser(models.Model):
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
email = models.EmailField(max_length=254)
creation_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.first_name, self.last_name
from django import forms
from django.forms import ModelForm
from myuserform.models import NewUser
# Create the form class.
class NewUserForm(ModelForm):
class Meta:
model = NewUser
fields = ['first_name', 'last_name', 'email']
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<title>{% block title %}My amazing site homepage{% endblock %}</title>
</head>
<body>
<div id="content">
{% block content %}{% endblock %}
</div>
</body>
</html>
{% extends "base.html" %}
{% block title %}My amazing Registration Form{% endblock %}
{% block content %}
<h1>{{title}}</h1><br>
<div class="container">
<div class="row">
<div class="col-md-6">
<section>
<div class="wizard">
<div class="wizard-inner">
<div class="connecting-line"></div>
<ul class="nav nav-tabs" role="tablist">
<li role="presentation" class="active">
<a href="#step1" data-toggle="tab" aria-controls="step1" role="tab" title="Step 1">
<span class="round-tab">
<i class="glyphicon glyphicon-folder-open"></i>
</span>
</a>
</li>
<li role="presentation" class="disabled">
<a href="#step2" data-toggle="tab" aria-controls="step2" role="tab" title="Step 2">
<span class="round-tab">
<i class="glyphicon glyphicon-pencil"></i>
</span>
</a>
</li>
<li role="presentation" class="disabled">
<a href="#step3" data-toggle="tab" aria-controls="step3" role="tab" title="Step 3">
<span class="round-tab">
<i class="glyphicon glyphicon-picture"></i>
</span>
</a>
</li>
<li role="presentation" class="disabled">
<a href="#complete" data-toggle="tab" aria-controls="complete" role="tab" title="Complete">
<span class="round-tab">
<i class="glyphicon glyphicon-ok"></i>
</span>
</a>
</li>
</ul>
</div>
<form role="form" id="login-form" action="#" method="post">
{% csrf_token %}
<div class="tab-content">
<div class="tab-pane active" role="tabpanel" id="step1">
<div class="step1">
<div class="row">
<div class="col-md-6">
<label for="exampleInputEmail1">First Name</label>
<input type="text" name="first_name" class="form-control" id="exampleInputEmail1" placeholder="First Name">
</div>
</div>
</div>
<ul class="list-inline pull-right">
<li><button type="button" name="first_step" class="btn btn-primary" onclick="getFirstNameMove()">Save and continue</button></li>
</ul>
</div>
<div class="tab-pane" role="tabpanel" id="step2">
<div class="step2">
<div class="step-22">
<label for="exampleInputEmail1">Last Name</label>
<input type="text" name="last_name" class="form-control" id="exampleInputEmail2" placeholder="Last Name">
</div>
</div>
<ul class="list-inline pull-right">
<li><button type="button" class="btn btn-default prev-step">Previous</button></li>
<li><button type="button" name="second_step" class="btn btn-primary" onclick="getLastNameMove()">Save and continue</button></li>
</ul>
</div>
<div class="tab-pane" role="tabpanel" id="step3">
<div class="step3">
<div class="step-33">
<label for="exampleInputEmail1">email</label>
<input type="email" name="email" class="form-control" id="exampleInputEmail3" placeholder="email address">
</div>
<ul class="list-inline pull-right">
<li><button type="button" class="btn btn-default prev-step">Previous</button></li>
<li><button type="button" name="final_step" id="final_step" class="btn btn-primary btn-info-full" onclick="getEmailMove()">Save and continue</button></li>
</ul>
</div>
</div>
<div class="tab-pane" role="tabpanel" id="complete">
<div class="step44">
<h5>Completed</h5>
</div>
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</section>
</div>
</div>
</div>
<script type="text/javascript">
$ = jQuery.noConflict();
$(document).ready(function () {
//Initialize tooltips
$('.nav-tabs > li a[title]').tooltip();
//Wizard
$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
var $target = $(e.target);
if ($target.parent().hasClass('disabled')) {
return false;
}
});
$(".next-step").click(function (e) {
var $active = $('.wizard .nav-tabs li.active');
$active.next().removeClass('disabled');
nextTab($active);
});
$(".prev-step").click(function (e) {
var $active = $('.wizard .nav-tabs li.active');
prevTab($active);
});
});
function getFirstNameMove() {
if (checkFirstName()) {
moveNextTab();
}
}
function getLastNameMove() {
if (checkLastName()) {
moveNextTab();
}
}
function getEmailMove() {
if (checkEmail()) {
moveNextTab();
sendNuData();
}
}
function checkFirstName() {
form = document.getElementById('login-form');
if (form.first_name.value == '') {
alert('Cannot leave First name field blank.');
form.first_name.focus();
return false;
}
return true;
}
function checkLastName() {
form = document.getElementById('login-form');
if (form.last_name.value == '') {
alert('Cannot leave Last name field blank.');
form.last_name.focus();
return false;
}
return true;
}
function checkEmail() {
form = document.getElementById('login-form');
let newEmail = form.email.value;
if (newEmail == '') {
alert('Cannot leave email field blank.');
form.email.focus();
return false;
}
if (emailValidate(newEmail)) {
return true;
} else {
alert('Please provide a valid email address.');
form.email.focus();
return false;
}
}
function emailValidate(sEmail) {
let filter = /^([\w-.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$/;
return filter.test(sEmail);
}
function moveNextTab() {
var $active = $('.wizard .nav-tabs li.active');
$active.next().removeClass('disabled');
nextTab($active);
}
function nextTab(elem) {
$(elem).next().find('a[data-toggle="tab"]').click();
}
function prevTab(elem) {
$(elem).prev().find('a[data-toggle="tab"]').click();
}
function sendNuData(){
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
$.ajax({
url: '/get_allform_data/',
method: 'post',
data: $('form').serialize(),
contentType: false,
success: function (data) {
alert('Form Submitted');
// console.log(data);
},
error: function(data) {
alert('Form submission failed');
// console.log(data);
}
});
}
//according menu
$(document).ready(function()
{
//Add Inactive Class To All Accordion Headers
$('.accordion-header').toggleClass('inactive-header');
//Set The Accordion Content Width
var contentwidth = $('.accordion-header').width();
$('.accordion-content').css({});
//Open The First Accordion Section When Page Loads
$('.accordion-header').first().toggleClass('active-header').toggleClass('inactive-header');
$('.accordion-content').first().slideDown().toggleClass('open-content');
// The Accordion Effect
$('.accordion-header').click(function () {
if($(this).is('.inactive-header')) {
$('.active-header').toggleClass('active-header').toggleClass('inactive-header').next().slideToggle().toggleClass('open-content');
$(this).toggleClass('active-header').toggleClass('inactive-header');
$(this).next().slideToggle().toggleClass('open-content');
}
else {
$(this).toggleClass('active-header').toggleClass('inactive-header');
$(this).next().slideToggle().toggleClass('open-content');
}
});
return false;
});
</script>
{% endblock %}
contentType: "application/x-www-form-urlencoded",
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name') # and so on...
from django.template import Template, Context
from django.template.loader import get_template
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse, HttpRequest
from django.urls import reverse
from .forms import NewUserForm
from .models import NewUser
from django.forms import Select, ModelForm
import datetime
from django.views.decorators.csrf import csrf_protect
from django.http import QueryDict
import json
import copy
def index(request):
return HttpResponse("Hello, world. You're at the myuserform index.")
@csrf_protect
def regform(request):
title = "This is the Registration Form Page"
return render(request, 'regform.html', {'title': title})
@csrf_protect
def get_allform_data(request):
# you can check if request is ajax
# and you could handle other calls differently
# if request.is_ajax() - do this and do that...
# we create an empty Querydict to copy the request into it
# to be able to handle/modify input request data sent by AJAX
datam = QueryDict()
# we should copy the request to work with it if needed
for i in request:
datam = copy.copy(i)
# the AJAX sent request is better in normal dictionary format
post_dict = QueryDict(datam).dict()
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
# however with using AJAX request.POST is empty - so we use the request Querydict
# to populate the Form
form = NewUserForm(post_dict)
# check whether it's valid:
if form.is_valid():
# you can do whatever with cleaned form data
data = form.cleaned_data
# we can now save the form input data to the database
form.save()
# print("form is now saved")
# return HttpResponse("I got the data and saved it")
else:
print(form.errors)
else:
form = NewUserForm() # this not really needed here, only if we handle the whole in 1 view
# return HttpResponse("I cannot handle the request yet, since it was not sent yet")
return HttpResponseRedirect(reverse('regform'))
return render(request, 'regform.html', {'form' : form })
@csrf_protect
def get_allform_data(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NewUserForm(request.POST)
# check whether it's valid:
if form.is_valid():
# you can still do whatever with the cleaned data here
data = form.cleaned_data
# and you just save the form (inputs) to the database
form.save()
else:
print(form.errors)
else:
form = NewUserForm() # this not really needed here, only if we handle the whole in 1 view
# return HttpResponse("I cannot handle the request yet, since it was not sent yet")
return HttpResponseRedirect(reverse('regform'))
return render(request, 'regform.html', {'form' : form })
from django.contrib import admin
from django.urls import include, path
from myuserform import views as myuserform_views
urlpatterns = [
path('', myuserform_views.index),
path('regform/', myuserform_views.regform, name='regform'),
path('admin/', admin.site.urls),
path('get_allform_data/', myuserform_views.get_allform_data)
]
关于javascript - 在 django 中处理单个 html 表单的多个输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53051664/
我有一个 html 格式的表单: 我需要得到 JavaScript在value input 字段执行,但只能通过表单的 submit .原因是页面是一个模板所以我不控制它(不能有
我管理的论坛是托管软件,因此我无法访问源代码,我只能向页面添加 JavaScript 来实现我需要完成的任务。 我正在尝试用超链接替换所有页面上某些文本关键字的第一个实例。我还根据国家/地区代码对这些
我正在使用 JS 打开新页面并将 HTML 代码写入其中,但是当我尝试使用 document.write() 在新页面中编写 JS 时功能不起作用。显然,一旦看到 ,主 JS 就会关闭。用于即将打开的
提问不是为了解决问题,提问是为了更好地理解系统 专家!我知道每当你将 javascript 代码输入 javascript 引擎时,它会立即由 javascript 引擎执行。由于没有看过Engi
我在一个文件夹中有两个 javascript 文件。我想将一个变量的 javascript 文件传递到另一个。我应该使用什么程序? 最佳答案 window.postMessage用于跨文档消息。使
我有一个练习,我需要输入两个输入并检查它们是否都等于一个。 如果是 console.log 正则 console.log false 我试过这样的事情: function isPositive(fir
我正在做一个Web应用程序,计划允许其他网站(客户端)在其页面上嵌入以下javascript: 我的网络应用程序位于 http://example.org 。 我不能假设客户端网站的页面有 JQue
目前我正在使用三个外部 JS 文件。 我喜欢将所有三个 JS 文件合而为一。 尽一切可能。我创建 aio.js 并在 aio.js 中 src="https://code.jquery.com/
我有例如像这样的数组: var myArray = []; var item1 = { start: '08:00', end: '09:30' } var item2 = {
所以我正在制作一个 Chrome 扩展,它使用我制作的一些 TamperMonkey 脚本。我想要一个“主”javascript 文件,您可以在其中包含并执行其他脚本。我很擅长使用以下行将其他 jav
我有 A、B html 和 A、B javascript 文件。 并且,如何将 A JavaScript 中使用的全局变量直接移动到 B JavaScript 中? 示例 JavaScript) va
我需要将以下整个代码放入名为 activate.js 的 JavaScript 中。你能告诉我怎么做吗? var int = new int({ seconds: 30, mark
我已经为我的 .net Web 应用程序创建了母版页 EXAMPLE1.Master。他们的 I 将值存储在 JavaScript 变量中。我想在另一个 JS 文件中检索该变量。 示例1.大师:-
是否有任何库可以用来转换这样的代码: function () { var a = 1; } 像这样的代码: function () { var a = 1; } 在我的浏览器中。因为我在 Gi
我收到语法缺失 ) 错误 $(document).ready(function changeText() { var p = document.getElementById('bidp
我正在制作进度条。它有一个标签。我想调整某个脚本完成的标签。在找到可能的解决方案的一些答案后,我想出了以下脚本。第一个启动并按预期工作。然而,第二个却没有。它出什么问题了?代码如下: HTML:
这里有一个很简单的问题,我简单的头脑无法回答:为什么我在外部库中加载时,下面的匿名和onload函数没有运行?我错过了一些非常非常基本的东西。 Library.js 只有一行:console.log(
我知道 javascript 是一种客户端语言,但如果实际代码中嵌入的 javascript 代码以某种方式与在控制台上运行的代码不同,我会尝试找到答案。让我用一个例子来解释它: 我想创建一个像 Mi
我如何将这个内联 javascript 更改为 Unobtrusive JavaScript? 谢谢! 感谢您的回答,但它不起作用。我的代码是: PHP js文件 document.getElem
我正在寻找将简单的 JavaScript 对象“转储”到动态生成的 JavaScript 源代码中的最优雅的方法。 目的:假设我们有 node.js 服务器生成 HTML。我们在服务器端有一个对象x。
我是一名优秀的程序员,十分优秀!