修改views使用class模式
类模式写views - 免去了函数模式的判断的烦恼
users/views.py
from django.views.generic import View
class UserView(View):#继承了View类,它里面实现get post等方法, 使用类模式写免去了函数模式的判断
def get(self, request):
return render(request, "login.html", {})
def post(self, request):
user_name = request.POST.get("username", "")
pass_word = request.POST.get("password", "")
user = authenticate(username=user_name, password=pass_word)
if user is not None: # 用户名密码验证成功
login(request, user) # django执行用户登录
return render(request, "index.html")
else:
return render(request, "login.html", {\'msg\': "用户名或密码错误"})
函数模式写views - 需要手动判断方法,有点麻烦
users/views_old.py
def user_login(request):
if request.method == "POST":
user_name = request.POST.get("username", "")
pass_word = request.POST.get("password", "")
user = authenticate(username=user_name, password=pass_word)
if user is not None: # 用户名密码验证成功
login(request, user) # django执行用户登录
return render(request, "index.html")
else:
return render(request, "login.html", {\'msg\': "用户名或密码错误"})
elif request.method == "GET":
return render(request, "login.html", {})
修改urls.py 调用views里对应的类
from django.views.generic import TemplateView
from users import views
urlpatterns = [
path(\'\', TemplateView.as_view(template_name=\'index.html\'), name="index"),
path(\'login/\', views.UserView.as_view(), name="login"),
path(\'xadmin/\', xadmin.site.urls),
]