小可爱从0搭建网站(4)
作者:互联网
用户登入--案例
urls.py
"""MyDjango_world URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app01 import views
# # 后期常用的操作就是在URL添加对应关系,在views里面写视图函数处理请求
urlpatterns = [
# 案例---用户登入
path('login/', views.login), # 返回 一个 redir
]
views.py
from django.shortcuts import render
# Create your views here.
# 后期常用的操作就是在URL添加对应关系,在views里面写视图函数处理请求
from django.shortcuts import render, HttpResponse,redirect
# 案例---用户登入
def login(request):
if request.method == "GET":
return render(request, "login.html")
# 如果是POST请求,获取用户提交的数据
# print(request.POST)
username = request.POST.get("user")
password = request.POST.get("pwd")
if username == "root" and password == "123":
# return HttpResponse("登入成功")
return redirect("www.baidu.com")
return render(request,"login.html",{"error_msg": "用户名或密码错误"})
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登入</title>
</head>
<body>
<h1>用户登入</h1>
<hr/><!换行符>
<from method="post" action="/login/">
{% csrf_token %}
<input type="text" name="user" placeholder="用户名">
<input type="password" name="pwd" placeholder="密码">
<input type="submit" value="提交"/>
<span style="color:red;">{{ error_msg }}</span>
</from>
</body>
</html>
标签:views,网站,request,URL,小可爱,登入,path,import,搭建 来源: https://blog.csdn.net/weixin_40686234/article/details/123028185