码迷,mamicode.com
首页 > 其他好文 > 详细

[py][mx]django使用class写views-免去判断方法的烦恼

时间:2018-02-01 10:38:25      阅读:1610      评论:0      收藏:0      [点我收藏+]

标签:logs   django   dex   错误   pos   执行   xadmin   code   down   

修改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),
]

技术分享图片

[py][mx]django使用class写views-免去判断方法的烦恼

标签:logs   django   dex   错误   pos   执行   xadmin   code   down   

原文地址:https://www.cnblogs.com/iiiiiher/p/8397449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!