django form表单和代码 处理登录用户名字密码
#_*_encoding:utf-8_*_
from django.contrib.authimport authenticate, login
# Create your views here.
from django.contrib.auth.backendsimport ModelBackend
from django.shortcutsimport render
from .modelsimport UserProfile
from django.db.modelsimport Q
from django.views.generic.baseimport View
from .formsimport LoginForm
class LoginView(View):
#无需判断是get还是post def get() 这个方法会自动判断
def get(self,request):
return render(request,"login.html",{})
def post(self,request):
login_form= LoginForm(request.POST)
if login_form.is_valid():
user_name= request.POST.get("username","")
pass_word= request.POST.get("password","")
user= authenticate(username=user_name,password=pass_word)
if useris not None:
login(request, user)
return render(request,"index.html")
else:
return render(request,"login.html", {"msg": u"用户名密码错误"})
else:
return render(request,"login.html",{"login_form":login_form})
class CustomBackend(ModelBackend):
def authenticate(self,username=None,password=None,**kwargs):
try:
user= UserProfile.objects.get(Q(username = username)|Q(email=username))
if user.check_password(password):
return user
except Exception as e:
return None
# 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)
# return render(request,"index.html")
# else:
# return render(request,"login.html",{"msg":u"用户名密码错误"})
#
#
# elif request.method == "GET":
# return render(request,"login.html",{})
#_*_encoding:utf-8_*_
__author__= 'Administrator'
__time__= '2018/1/13 12:44'
from djangoimport forms
class LoginForm(forms.Form):
username= forms.CharField(required=True)
password= forms.CharField(required=True,min_length=5)
{# #}
用 户 名
密 码
{%for key,error in login_form.errors.items %}{{error }}{%endfor %}{{msg }}">
{# #}
{%csrf_token %}