用户登录
创建一个app单独作为用户使用
新建app需要配置的三个步骤:
1.新建一个accounts的app
python manage.py startapp accounts
2.配置url
#主url
url(r'^accounts/', include("accounts.urls")),
#app里面的url配置
(env) [root@ES-10-1-21-55-B28 accounts]# cat urls.py from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^login/$', views.login_view, name='user_login'), #name名字为给login 或者视图一个名字,通过名字反查视图和url名字 ]
3.激活app
INSTALLED_APPS = ( …… ’accounts', )
用户登录:
1.获取提交过来的用户名和密码
2.根据用户名查询用户密码
3.判断用户的密码是否相同
示例:
from django.shortcuts import render from django.contrib.auth import authenticate,login,logout from django.http import HttpResponse # Create your views here. def login_view(request): if request.method=="GET": return render(request,"login.html") else: username=request.POST.get("username","")#给一个空的默认值防止报错 userpass=request.POST.get("userpass","")# user = authenticate(username=username,password=userpass) if user is not None: pass if user.is_active: login(request,user) return HttpResponse("登录成功") else: return HttpResponse("用户名密码正确,但用户被禁用") else: return HttpResponse("用户名密码错误")
In [54]: from django.contrib.auth.models import User In [55]: u=User.objects.get(username="rock") In [56]: u.is_active Out[56]: False In [57]: from django.contrib.auth import authenticate In [58]: authenticate(username="rock",password="123456") In [59]: a=authenticate(username="rock",password="123456") In [60]: a In [61]: u.is_active=True In [62]: a=authenticate(username="rock",password="123456") #这个版本的django判断用户当用户is_active为False时候,用户登录返回结果直接为空 In [63]: a In [64]: u.save() In [65]: a In [66]: a=authenticate(username="rock",password="123456") In [67]: a Out[67]: <User: rock>
用户登录添加模板
Django配置
1.配置静态文件
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )
2.配置时区
TIME_ZONE = ’Asia/Shanghai’