- 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/
对于 Metal ,如果对主纹理进行 mipmap 处理,是否还需要对多采样纹理进行 mipmap 处理?我阅读了苹果文档,但没有得到任何相关信息。 最佳答案 Mipmapping 适用于您将从中
我正在使用的代码在后端 Groovy 代码中具有呈现 GSP(Groovy 服务器页面)的 Controller 。对于前端,我们使用 React-router v4 来处理路由。我遇到的问题是,通过
我们正在 build 一个巨大的网站。我们正在考虑是在服务器端(ASP .Net)还是在客户端进行 HTML 处理。 例如,我们有 HTML 文件,其作用类似于用于生成选项卡的模板。服务器端获取 HT
我正在尝试将图像加载到 void setup() 中的数组中,但是当我这样做时出现此错误:“类型不匹配,'processing .core.PImage' does not匹配“processing.
我正在尝试使用其私有(private)应用程序更新 Shopify 上的客户标签。我用 postman 尝试过,一切正常,但通过 AJAX,它带我成功回调而不是错误,但成功后我得到了身份验证链接,而不
如何更改我的 Processing appIconTest.exe 导出的默认图标在窗口中的应用程序? 默认一个: 最佳答案 经过一些研究,我能找到的最简单的解决方案是: 进入 ...\process
我在 Processing 中做了一个简单的小游戏,但需要一些帮助。我有一个 mp3,想将它添加到我的应用程序中,以便在后台循环运行。 这可能吗?非常感谢。 最佳答案 您可以使用声音库。处理已经自带
我有几个这样创建的按钮: 在 setup() PImage[] imgs1 = {loadImage("AREA1_1.png"),loadImage("AREA1_2.png"),loadImage
我正在尝试使用 Processing 创建一个多人游戏,但无法弄清楚如何将屏幕分成两个以显示玩家的不同情况? 就像在 c# 中一样,我们有Viewport leftViewport,rightView
我一直在尝试使用 Moore 邻域在处理过程中创建元胞自动机,到目前为止非常成功。我已经设法使基本系统正常工作,现在我希望通过添加不同的功能来使用它。现在,我检查细胞是否存活。如果是,我使用 fill
有没有办法用 JavaScript 代码检查资源使用情况?我可以检查脚本的 RAM 使用情况和 CPU 使用情况吗? 由于做某事有多种方法,我可能会使用不同的方法编写代码,并将其保存为两个不同的文件,
我想弄清楚如何处理这样的列表: [ [[4,6,7], [1,2,4,6]] , [[10,4,2,4], [1]] ] 这是一个整数列表的列表 我希望我的函数将此列表作为输入并返回列表中没有重复的整
有没有办法在不需要时处理 MethodChannel/EventChannel ?我问是因为我想为对象创建多个方法/事件 channel 。 例子: class Call { ... fields
我有一个关于在 Python3 中处理 ConnectionResetError 的问题。这通常发生在我使用 urllib.request.Request 函数时。我想知道如果我们遇到这样的错误是否可
我一直在努力解决这个问题几个小时,但无济于事。代码很简单,一个弹跳球(粒子)。将粒子的速度初始化为 (0, 0) 将使其保持上下弹跳。将粒子的初始化速度更改为 (0, 0.01) 或任何十进制浮点数都
我把自己弄得一团糟。 我想在我的系统中添加 python3.6 所以我决定在我的 Ubuntu 19.10 中卸载现有的。但是现在每次我想安装一些东西我都会得到这样的错误: dpkg: error w
我正在努力解决 Rpart 包中的 NA 功能。我得到了以下数据框(下面的代码) Outcome VarA VarB 1 1 1 0 2 1 1 1
我将 Java 与 JSF 一起使用,这是 Glassfish 3 容器。 在我的 Web 应用程序中,我试图实现一个文件(图像)管理系统。 我有一个 config.properties我从中读取上传
所以我一直在Processing工作几个星期以来,虽然我没有编程经验,但我已经转向更复杂的项目。我正在编写一个进化模拟器,它会产生具有随机属性的生物。 最终,我将添加复制,但现在这些生物只是在屏幕上漂
有人知道 Delphi 2009 对“with”的处理有什么不同吗? 我昨天解决了一个问题,只是将“with”解构为完整引用,如“with Datamodule、Dataset、MainForm”。
我是一名优秀的程序员,十分优秀!