登录
1.视图函数views.py
# 登录 from django.contrib.auth import authenticate, login # authenticate:user认证 login:用户登录并记录session class LoginView(View): '''登录''' def get(self, request): '''显示登录页面''' # 判断是否记住用户名 if 'username' in request.COOKIES: username = request.COOKIES.get('username') checked = 'checked' else: username= '' checked = '' # 使用模板 return render(request, 'login.html', {'username':username, 'checked':checked}) def post(self, request): '''登录校验''' # 接收数据 username = request.POST.get('username') password = request.POST.get('pwd') # 校验数据 if not all([username, password]): return render(request, 'login.html', {'errmsg':'数据不完整'}) user = authenticate(username=username, password=password) # 查找数据库,有的话返回user信息 没有的话返回None if user is not None: # 用户名和密码正确 # 验证是否激活 if user.is_active: # 用户已激活 # 记录用户登录状态 login(request, user) # django.contrib.auth中的login方法 # 跳转到首页 response = redirect(reverse('goods:index')) # HttpResponseRedirct # 判断是否要记住用户名 remember = request.POST.get('remember') if remember == 'on': # 记住用户名 response.set_cookie('username', username, max_age=7*24*3600) # 记录cookie else: response.delete_cookie('username') # 返回response return response else: return render(request, 'login.html', {'errmsg':'用户尚未激活'}) else: # 用户名或密码错误 return render(request, 'login.html', {'errmsg':'用户名或密码错误'})
2.模板login.html
<form method="post"> {% csrf_token %} <input type="text" name="username" class="name_input" value="{{ username }}" placeholder="请输入用户名"> <div class="user_error">输入错误</div> <input type="password" name="pwd" class="pass_input" placeholder="请输入密码"> <div class="pwd_error">输入错误</div> <div class="more_input clearfix"> <input type="checkbox" name="remember" {{ checked }}> <label>记住用户名</label> <a href="#">忘记密码</a> </div> <input type="submit" name="" value="登录" class="input_submit"> </form>
3.使用django-redis
django-redis文档:https://django-redis-chs.readthedocs.io/zh_CN/latest/
配置settings.py文件
# django缓存配置 CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://192.168.199.130:6379/9", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } # 存储在缓存中:存储在本机内存中,如果丢失则不能找回,比数据库的方式读写更快。 SESSION_ENGINE = "django.contrib.sessions.backends.cache" SESSION_CACHE_ALIAS = "default"
报错
Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/python/.virtualenvs/bj19/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/db/models/base.py", line 117, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/db/models/base.py", line 321, in add_to_class value.contribute_to_class(cls, name) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/db/models/options.py", line 204, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/db/__init__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/db/utils.py", line 201, in __getitem__ backend = load_backend(db['ENGINE']) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/home/python/.virtualenvs/bj19/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/python/.virtualenvs/bj19/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 36, in <module> raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__) django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
原因django-redis版本是4.10.0 不支持django1.8.2 自动把django版本升到了2.2.5
pip install django-redis==4.7.0
退出
视图函数views.py
# 退出 from django.contrib.auth import logout # logout:退出并清除session信息 class LogoutView(View): def get(self, request): '''退出页面''' # 退出并清除session信息 logout(request) # 跳转到首页 return redirect(reverse('goods:index'))