django

Django-22 云笔记项目

2021-07-19  本文已影响0人  JuliusL

一、初始配置

1,创建项目

django-admin startproject tedu_note

2,创建应用

cd tedu_not
python3 manage.py startapp user

3,进入mysql命令行,创建数据库

注意:default charset utf8 一定要加上

mysql -u root -p
create database tedu_note default charset utf8;

4,配置settings.py

1,安装user应用
2,注释csrf,防止post403
3,常规数据库配置
4,改语言,改时区

...
INSTALLED_APPS=[
  ...
  'user',
]
...
MIDDLEWARE = [
  ...
 #'django.middleware.csrf.CsrfViewMiddleware',
  ...
]
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'tedu_note',
        'USER':'root',
        'PASSWORD':'123456',
        'HOST':'127.0.0.1',
        'PORT':'3306'
    }
}
...
LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

* 如果提示报错:NameError: name '_mysql' is not defined

需要在init.py中加如下代码:

import pymysql
pymysql.version_info = (1, 4, 13, "final", 0)
pymysql.install_as_MySQLdb()

哈希算法 - 给明文,计算出一段定长的,不可逆的值:md5,sha-256

import hashlib.md5()

m = hashlib.md5()
m.update(b'123456')
m.hexdigest() #十六进制可视字符,适合存储
m.digest() #带不可视字符的,适合计算

代码

Templates

1,首页

index/templates/index/index.html

<body>

{% if request.session.username %}
<p>
     欢迎 {{ request.session.username }}
</p>
<p>
    <a href="/user/logout">退出登录</a>
</p>
<p>
    <a href="">进入我的笔记</a>
</p>
{% else %}
    {% if requset.COOKIES.username %}
    <p>
    欢迎{{ request.session.username }}
    </p>
    <p>
    <a href="/user/logout">退出登录</a>
    </p>
    <p>
        <a href="">进入我的笔记</a>
    </p>
    {% else %}
    <p>
        <a href="/user/login">登录</a>
    </p>
     <p>
        <a href="/user/reg">注册</a>
    </p>
    {% endif %}
{% endif %}
</body>

2,登录页

user/templates/user/login.html

<body>
    <form action="/user/login" method="POST">
        用户名<input type="text" name="username">
        <br>
        密码<input type="password" name="password">
        <br>
        <input type="checkbox" name="remember">记住用户名
        <br>
        <input type="submit" value="登陆">
    </form>
</body>

3,注册页

user/templates/user/register.html

<body>
    <form action="/user/reg" method="POST">
        用户名:<input type="text" name="username"><br>
        密码:<input type="password" name="password_1"><br>
        确认密码<input type="password" name="password_2"><br>
        <input type="submit" value="注册">
    </form>
</body>

4,添加笔记页

note/templates/note/add_note.html

<body>
<form action='/note/add' method="POST">
    <p>
        标题:<input type='text' name="title">
        <input type="submit" value="保存">
    </p>
    <p>
        <textarea cols="30" rows="10" name="content"></textarea>
    </p>
</form>
</body>

Models

1,Note

note/models.py

from django.db import models
from user.models import User
class Note(models.Model):
    title = models.CharField('标题',max_length=100)
    content = models.TextField('内容')
    created_time = models.DateTimeField('创建时间',auto_now_add=True)
    updated_time = models.DateTimeField('更新时间',auto_now=True)
    user=models.ForeignKey(User,on_delete=models.CASCADE)

2,User

note/models.py

from django.db import models

class User(models.Model):

    username = models.CharField("用户名",max_length=30,unique=True)
    password = models.CharField("密码",max_length=32)
    created_time = models.DateTimeField("创建时间",auto_now_add=True)
    updated_time = models.DateTimeField("更新时间",auto_now=True)

    def __str__(self):
        return "用户"+self.username

    class Meta:
        db_table = ''
        managed = True
        verbose_name = 'User'
        verbose_name_plural = 'Users'

Views

1,user

user/views.py

from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .models import User 
import hashlib

# Create your views here.
def reg_view(request):
    #注册
    if request.method == 'GET':
        #GET 返回页面
        return render(request,'user/register.html')
    elif request.method == 'POST':
         #POST 处理提交数据
        username = request.POST['username']
        password_1 = request.POST['password_1']
        password_2 = request.POST['password_2']
        #   1. 两个密码要保持一致
        if password_1 != password_2:
            return HttpResponse("两次密码输入不一致")
        #   2. 当前用户名是否可用
        old_users = User.objects.filter(username = username)
        if old_users:
            return HttpResponse("用户名已注册")
        
        m = hashlib.md5()
        # 注意:update只接收字节串,而password_1是字符串,要encode一下
        m.update(password_1.encode())
        password_m = m.hexdigest()
        #   3. 插入数据 [明文处理密码]
        try:
            user = User.objects.create(username=username,password = password_m)
        except Exception as e:
            # 有可能报错 - 重复插入 [唯一索引注意并发写入问题]
            print('--create user error %s'%(e))
            return HttpResponse('用户名已注册')

        # 免登陆一天
        request.session['username'] = username
        request.session['uid'] = user.id
        #todo 修改session存储时间为1天


        # return HttpResponseRedirect("注册成功")
        return HttpResponseRedirect("/index")
    
def login_view(request):
    if request.method == 'GET':
        #  获取登录页面
        #检查登录状态,如果登录了,显示 已登录
        if request.session.get('username') and request.session.get('uid'):
            # return HttpResponse('已登录')
            return HttpResponseRedirect("/index")
        #检查Cookie
        c_username = request.COOKIES.get('username')
        c_uid = request.COOKIES.get('uid')
        if c_username and c_uid:
            # 回写session
            request.session['username'] = c_username
            request.session['uid'] = c_uid
            # return HttpResponse('已登录')
            return HttpResponseRedirect("/index")

        return render(request,'user/login.html')
    elif request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = User.objects.get(username=username)
        if not user:
            return HttpResponse("用户不存在")
        m = hashlib.md5()
        m.update(password.encode())
        if m.hexdigest() != user.password:
            return HttpResponse("登陆失败,密码错误")
        
        #记录会话状态
        request.session['username'] = username
        request.session['uid'] = user.id

        resp = HttpResponseRedirect("/index")#HttpResponse('登陆成功')

        # 判断用户是否点选了 '记住用户名'
        if 'remember' in request.POST:
            # 选中了 -> Cookies 存储 username,uid 时间3天
            resp.set_cookie('username',username,3600*24*3)
            resp.set_cookie('uid',user.id,3600*24*3)

        return resp

#登出
def logout_view(request):
    # 删session 和 cookie
    if 'username' in request.session:
        del request.session['username']
    if 'uid' in request.session:
        del request.session['uid']

    resp = HttpResponseRedirect('/index')
    if 'username' in request.COOKIES:
        resp.delete_cookie('username')
    if 'uid' in request.COOKIES:
        resp.delete_cookie('uid')
    return resp

2,note

note/views.py

from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .models import Note

#校验登录状态的装饰器写法
def check_login(fn):
    def wrap(request,*args,**kwargs):
        if 'username' not in request.session or 'uid' not in request.session:
            #检查cookies
            c_username = request.COOKIES.get('username')
            c_uid = request.COOKIES.get('uid')
            if not c_username or not c_uid:
                return HttpResponseRedirect('/user/login')
            else:
                #回写session
                request.session['username'] = c_username
                request.session['uid'] = c_uid

        return fn(request,*args,**kwargs)
    return wrap

# Create your views here.
@check_login
def add_note(request):
    if request.method == 'GET':
        return render(request,'note/add_note.html')
    elif request.method == 'POST':
        #处理数据
        uid = request.session['uid']
        title = request.POST['title']
        content = request.POST['content']
        Note.objects.create(title='title',content = content,user_id=uid)
        return HttpResponse('添加笔记成功')

urls

1,tedu_note.urls

tedu_note/urls.py

from django.contrib import admin
from django.urls import path,include
from index import views as index_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('user/',include('user.urls')),
    path('index',index_views.index_view),
    path('note/',include('note.urls'))
]

2,user.urls

user/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('reg',views.reg_view),
    path('login',views.login_view),
    path('logout',views.logout_view),
]

3,note.urls

note/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('add',views.add_note)
]
上一篇下一篇

猜你喜欢

热点阅读