Django-- login feature

Login function:

  1, if not slash routing access, plus an internal routing will redirect slash

 

All html files to uninstall the default templates folder below

All (css, js, front-end third-party libraries) are placed in static default folder

html page the way the introduction of external resources

  1、cdn

  2, local

 

Static configuration file:

= STATIC_URL ' / static / ' 
# static file configuration 
STATICFILES_DIRS = [ 
    os.path.join (base_dir, ' static ' ) 
] 
# exposed to the outside world can still access the server folder below all the resources 


STATIC_URL = ' / xxx / '   # Interface prefix the name of your relationship with a little static folder are not 
# default prefix with the static folder name under the same circumstances! ! ! 
# Static file configuration 
STATICFILES_DIRS = [ 
    os.path.join (base_dir, ' static ' ),   # is your static folder path 
    os.path.join (base_dir, ' static1 ' ),
    os.path.join (base_dir, ' static2 ' ) 
] 
# PS: Find words will be followed by a list of all of the static files to find the path to stop immediately return a 404 not found

 

 

Starting form form submitting data in two ways:

<input type="submit">
<button></button>

 

 

How to submit data to the specified address form and manner:

  The action attribute control address submitted

  the way:

    1, the full path

<form action="http://127.0.0.1:8000/login/">

 

    2, just write path suffix

<form action="/login/">

 

    3, do not write (default submission to the current path)

  form is the default form get request

 

 

 request.POST: is a large dictionary, which store all the data submitted by the client post


print (request.POST.get ( 'username')) # is not recommended

<QueryDict: {'username': ['william'], 'password': ['123']}>

print (request.POST.getlist ( 'username')) # recommend using this one-time value to get a list of all the elements
 

 

 Although there is a list of value but get get value when they are individual elements?

  The default value will only take the last element in the list

If they wish to take the entire contents of the list you need to use getlist

  Usage scenarios: the user's preference, checkbox ...

 

 GET request is the same principle, using the same method

 

Recommended version of the database connection:

def login(request):
    if request.method == 'POST':
        username = request.POST.get("username")
        password = request.POST.get('password')
        # print(username, password)
        conn = pymysql.connect(
            host='127.0.0.1',
            port=3306,
            user='root',
            password='123456',
            db='test',
            charset='utf8',
            autocommit=True,
        )
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute("select * from user_info where name=%s and password=%s", (username, password))
        user_info = cursor.fetchall()
        # print(user_info)
        if user_info:
            return HttpResponse('login_success!!!')
    return render(request, 'login.html')

 

 

Django connect to the local database (Database):

 

 For the first time to download the database drivers:

 

Fill in the username, password and the corresponding database, you can test the connection after the completion of:

Once created, if the situation can not be opened schemas appear, you must first right-click schemas, and then select Database Tools toolbar inside the Force Refresh to force a refresh.

 

 

 

 

 Django connect to the database:

  1, modify the configuration file (inside all keys need bigger )

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'user_info',
        'HOST': '127.0.0.1',
        'PORT': 3306,
        'USER': 'root',
        'PASSWORD': '123456'
    }
}

 

   2、告诉Django用pymysql替换它默认的mysql_db模块连接数据库

    方式一:在你的项目文件夹下面的__init__.py   

import pymysql

pymysql.install_as_MySQLdb()  # 告诉Django用pymysql代替mysqldb的连接数据库

    方式二:在你的应用文件夹下面的__init__.py 

 

 

 Django中的ORM:

  ORM:对象关系映射:

    类 --> 表

    对象 --> 表记录

    对象点属性 --> 记录中的某一个字段对应的值

  Django的orm不能自动帮你创建库,但时候自动帮你创建表

  提示:

    一个Django项目就是用一个库,不要多个Django项目使用一个

 

数据库迁移(同步)命令(重点):

  这两句话必须同时出现,不能缺少其中的一句。。。

  manage.py makemigrations --> 将你的数据库变动记录到一个小本本上面  

数据库变动的纪录

  python3 manage.py migrate --> 将你的数据库变动同步到数据库中

 

 编写注册功能:

def reg(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # # 方式一:
        # user_obj = models.User.objects.create(name=username, password=password)
        # user_obj.save()  # 对象调用save对象保存到数据库
        # 方式二:
        user_obj = models.User.objects.create(name=username, password=password)
        print(user_obj)
        return HttpResponse("register success!!!")
    return render(request, 'reg.html')

 

 

   通过POST请求提交数据到服务端,在服务端将用户的数据插入到数据库表中

 

 查询数据(获取数据库信息):

  user_list = models.User.objects.all()  --> select id, name, password from user;

  只要是QuerySet对象就可以点query来查看获取当前的QuerySet对象的内部的sql语句 

  query对象支持索引取值,但是不推荐使用,推荐使用自带的.first()帮你获取第一条数据

  需要注意的点:你获取到的数据到底是一个queryset对象还是一个数据对象,如果是数据对象的话就一定要调用first方法

 

 <a href="/reg/" class="btn btn-success">添加数据</a>
# 注意路:径的书写一定要加斜杠


# 利用a标签href属性,可以指定页面跳转的路径
# 在a标签内部添加路径,可以是全路径,但是更推荐止血后缀即可

  ps:视图函数必须返回HttpResponse对象 

查询数据的两种方式:

# 查询数据的方式一:
user = models.User.objects.filter(id=edit_id)
# filter当条件不存在的时候,会返回一个空的queryset对象
# 查询数据的方式二"
user_obj = models.User.objects.get(id=edit_id)  

# 用get可以直接拿到数据对象的本身,但是如果数据不存在就直接报错

 

 

   

  

删除数据:

def delete_user(request):
    delete_id = request.GET.get('delete_id')
    models.User.objects.filter(id=delete_id).delete()  #
    return redirect('/userlist/')

 

  .delete会将query内的所有的对象全部删除

  内部重定向:利用return redirect('/userlist/')  # 括号里面可以写 别人的网址,也可以写自己的路径,后面的那个反斜杠可以加可以不加,但是推荐加上,避免出现不必要的错误。

  

编辑数据库中的数据:

  修改当前数据对象:

    方式一:

user_obj = models.User.object.filter(id=edit_id).frist()
user_obj.name = user_name
user_obj.save()


# 这种方法如果不修改指定的数据就是原先已经存在的数据

 

  方式二:

  在编辑的时候,要先找到那一行数据,然后开启一个新的网页来进行编辑,编辑完之后,要进行重定向会userlist的页面。

  定向的时候可以直接使用update方法来进行修改数据,在使用update的时候会讲那一条字段中的所有信息进行修改 a

  提交数据的时候是用post请求提交的数据,然后直接在请求体中将数据拿出来进行修改。。。

# views
def
edit(request): if request.method == 'POST': username = request.POST.get("username") password = request.POST.get("password") # 更新数据 edit_id = request.POST.get('edit_id') models.User.objects.filter(id=edit_id).update(name=username, password=password) return redirect('/userlist/') # print(username, password) # edit_id = request.POST.get("username") # print(edit_id) # 更新数据库 # 现获取到ID edit_id = request.GET.get('edit_id') # 将该数据查询出来渲染到一个页面 # 查询数据的方式一: user_obj = models.User.objects.filter(id=edit_id).first() # 查询数据的方式二" # user_obj = models.User.objects.get(id=edit_id) # 拿到的数据的对象,如果数据不存在就直接报错 # print(user.pk, user.name, user.password) return render(request, 'edit.html', locals())

 

 

网页中的编辑:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <h1>编辑数据</h1>
        <div class="col-md-6 col-md-offset-3">
            <form action="" method="post">
                <input type="hidden" name="edit_id" value="{{ user_obj.pk }}">
                <p>username:<input type="text" name="username" value="{{ user_obj.name }}" class="form-control"></p>
                <p>password:<input type="text" name="password" value="{{ user_obj.password }}" class="form-control"></p>
                <input type="submit" class="btn btn-warning">
            </form>
        </div>
    </div>
</div>
</body>
</html>

 

 

 

修改模型层里面跟表相关的所有的数据,只要你修改了就必须重新执行数据库迁移命令:

  python3 manage.py makemigrations  将你的数据库变动记录到一个小本本上面

  python3 manage.py migrate  真正操作数据库

  这两句话是同时出现的,不能缺少其中一句。。。

 

  新建一个字段,

    就要添加字段名的默认值,直接添加在CharField中加一个default参数就可以了,就会自动将之前已经存在的数据自动加上你在添加的这个默认值。

  删除一个字段,就直接将那个字段删掉,然后在执行那两句话,之后就会自动删除了

  

Django请求生命周期:

 

图书管理系统表设计:

  书籍:id、title、price、publish_id(出版社ID)

  作者:id、name、age

  出版社:id、name、email

  book2author:id、book_id、author_id

  

  在设计表的时候,可以不写ID,会默认帮你创建一个主键ID

创建数据库表:

class Book(models.Model):
    # 不写ID会默认帮你创建一个主键ID
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_length=8, decimal_places=2, max_digits=2)
    # 一对多外键字段的建立
    publish = models.ForeignKey(to='Publish')  # 默认是和Publish表的ID字段建立连接
    # 多对多外键字段建在关联的两张表的任意一张都可以  建议你建在查询频率比较高的一张
    author = models.ManyToManyField(to='Author')
    # 多对多字段,不会显示到表的字段中


class Publish(models.Model):
    name = models.CharField(max_length=32)
    email = models.CharField(max_length=32)


class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField(max_length=32) 

 

 外键字段名 orm会自动在字段名后面加上_id,无论你的后面是否有ID都会在后面加上_id

 

Guess you like

Origin www.cnblogs.com/tulintao/p/11409235.html