表单提交可能会报错,注意一行代码就可以解决:
简单配置路由:
简单表单提交:
<form action="/index/" method="post"> <p><input type="text" name="username" placeholder="请输入用户名"></p> <p><input type="text" name="password" placeholder="请输入密码"></p> <p><input type="submit" value="提交"></p> </form>
可见上面的提交还是提交到当前方法:可以通过判断提交方式来判断是提交表单还是请求页面:
def index(request): #return HttpResponse("hello word") if request.method == 'POST': u = request.POST['username'] p = request.POST['password'] print(u,p) return render(request,'index.html')
这种接受如果,接受不到就会报错,所以都是这样接受的:
def index(request): #return HttpResponse("hello word") if request.method == 'POST': u = request.POST.get('username',None) p = request.POST.get('password',None) print(u,p) if u =='123' and p == '456': from django.shortcuts import redirect return redirect("http://www.baidu.com") return render(request,'index.html')
示例demo:
from django.shortcuts import render from django.shortcuts import HttpResponse #coding=utf-8 def index(request): #return HttpResponse("hello word") error_msg = '' if request.method == 'POST': u = request.POST.get('username',None) p = request.POST.get('password',None) print(u,p) if u =='123' and p == '456': from django.shortcuts import redirect return redirect("/index/") else: error_msg = "failse to login" return render(request,'index.html',{'error_msg':error_msg})
模板:
<form action="/index/" method="post"> <p><input type="text" name="username" placeholder="请输入用户名"></p> <p><input type="text" name="password" placeholder="请输入密码"></p> <p><input type="submit" value="提交">{{ error_msg }}</p> </form>