温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python django -- 简单注册/登陆/session

发布时间:2020-07-11 10:57:24 来源:网络 阅读:1151 作者:hqtmit 栏目:开发技术

注册 登陆 session

user.html

未使用{{useform}}而使用{{ userform.password }}形式便于后期css样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="." method="POST">
    {% csrf_token %}
    <div>username: <input type="text" name="username"> </div>
    <div>password: {{ userform.password }}</div>
    <div><input type="submit" value="注册" name="reg"> <input type="submit" value="登陆" name="login"> </div>

</form>
</body>
</html>
form.py
#/usr/bin/env python3

from django import  forms

class UserForm(forms.Form):
    username=forms.CharField()
    password=forms.CharField()
models.py
from django.db import  models
class User(models.Model):
    username=models.CharField(max_length=30)
    password=models.CharField(max_length=30)

    def __str__(self):
        return self.username
viesw.py
from django.shortcuts import render
from django.views.decorators.cache import  cache_page
from .models import  User
# Create your views here.
from django.http import  HttpResponse
from django.http import  HttpResponseRedirect
from djapp.forms import UserForm

def user(request):
    if request.method == 'POST':
        userform=UserForm(request.POST)
        if userform.is_valid():
            if request.POST.get('reg'):
                username=userform.cleaned_data['username']
                password=userform.cleaned_data['password']
                User.objects.create(username=username,password=password)
                # user=User()
                # user.username=username
                # user.password=password
                # user.save()

                return  HttpResponse("login 注册%s"%username)

            else:
                if request.session.get('user_id') == 3:
                    return  HttpResponse("session 登陆")

                else:
                    try:
                        user=User.objects.get(username=request.POST.get('username',None))
                    except Exception as e:
                        print(e)
                        return HttpResponse("找不到用户")
                    if user.password == request.POST.get('password'):
                        request.session['user_id']=user.id
                        return HttpResponse("登陆成功")
                    else:
                        return  HttpResponse("登陆失败")

    else:
        userform=UserForm()
        return render(request,'djapp/user.html',{'userform':userform})
网页

cookie保存sessionid
python django -- 简单注册/登陆/session

django_session表内容

python django -- 简单注册/登陆/session

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI