一、環境版本信息:
操作系統:windows10
Django版本:2.0.5
Python版本:3.6.4
Mysql版本: 5.5.53 安裝mysql
二、基礎信息
1、App中的模型models.py
from django.db import models
# Create your models here.
class users(models.Model): blog_username = models.CharField(max_length=20) blog_link = models.CharField(max_length=50) class account(models.Model): blog_account = models.CharField(max_length=20) blog_password = models.CharField(max_length=20) blog_username = models.CharField(max_length=20)
app_users表插入數據:
app_account表插入數據:
2、在模板文件夾中新建londing.html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
</head>
<body >
<form action="/londing" method="get">
賬號:<input type="text" name="account"> 密碼:<input type="text" name="password"> <input type="submit" value="登陸"> </form> </body> </html>
3、視圖views.py
from django.shortcuts import render
from App.models import users,account from django.http import HttpResponse # Create your views here.
def index(request): user = users.objects.get(id=1) context = {'user':user} return render(request, 'index.html', context) def londing_form(request): #添加表單頁面 context = {} return render(request,'landing.html',context) def londing(request): #數據接收和處理 if 'account' in request.GET: user_account = request.GET['account'] password = request.GET['password'] username = account.objects.get(blog_account = user_account).blog_username #在數據庫account表中獲取賬號對應的用戶名(昵稱) user = users.objects.get(blog_username = username) #在users表中獲取所有信息 context = {'user':user} return render(request, 'index.html', context) #在index.html中顯示信息
4、修改路徑urls.py
from django.contrib import admin
from django.urls import path from App import views urlpatterns = [ path('admin/', admin.site.urls), path(r'index/',views.index), path(r'londing_form/',views.londing_form), path(r'londing/',views.londing), ]
三、GET請求測試
上面的代碼都是以get請求寫的直接開啟服務器: python manage.py runserver
四、POST請求測試
1、修改landing.html 注意:action部分相比get請求結尾多了一個“/”
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
</head>
<body >
<form action="/londing/" method="post">
{% csrf_token %} csrf 全稱是 Cross Site Request Forgery。這是Django提供的防止偽裝提交請求的功能。POST 方法提交的表格,必須有此標簽。
賬號:<input type="text" name="account"> 密碼:<input type="text" name="password"> <input type="submit" value="登陸"> </form> </body> </html>
2、修改views.py中的londing函數
def londing(request):
if request.POST: user_account = request.POST['account'] password = request.POST['password'] username = account.objects.get(blog_account = user_account).blog_username user = users.objects.get(blog_username = username) context = {'user':user} return render(request, 'index.html', context)
3、測試