Django+mysql implements a simple web login page

Table of contents

1. Use pycharm to create a django project

2. Start django project verification

3. Configure the mysql database

1. Install the mysql database locally

1) Install the mysql database

2) Create a database yourself

2. Install pymysql

3. Configure mysql database

1) Add in _init_.py under the same name package of the project

 2) In the settings.py file, replace the content in DATABASES

4. Django default data migration

 1) Execute the migration, and migrate the original application model in the project to the database synchronously

 2) View data migration results

5. Create a background super administrator 

 4. Log in to the background system

1. Start the service

2. Log in to the background system

5. Create an app application

1. Command to create an application

 2. Configure the application in INSTALLED_APPS in settings

6. Configure application routing 

1. Configure the main route

2. Configure sub-application routing

3. Configure views

Seven, create html page

1. Determine whether the template configuration is correct

 2. Create a sample html page 

 8. Access

9. Optimize and implement simple get and post

1. Configure routing

2. Use the get method to realize

1) Configure the views page

2) Optimize the login page

3) Display the results

3. Use the post method to realize

1) Configure the views page

2) Optimize the login page

 3) Display the results

 10. Continue to optimize and use the database method for data judgment

1. Add the data model in model.py

2. Migrate the data model to the database

 3. Create data for subsequent operations

 4. Modify views.py

5. Verification

11. Realize registration

1. Registration page

2. Configure routing

3. Create a registration method

 4. Access verification

12. Anti-mapping database tables to django models


Preface: This article implements django from 0 to 1 to build a web page, realizes django connection to mysql database, simple get and post requests, etc.

1. Use pycharm to create a django project

Slightly, the professional version can be directly created

This is the third-party library created by initialization

2. Start django project verification

pycharm's terminal input

python manage.py runserver

 access:

 Small episode: Error at startup: 'DIRS': [os.path.join(BASE_DIR, 'templates')]
NameError: name 'os' is not defined

My solution is: import os at the head of the settings.py file

There are other methods on the Internet (the blogger did not try): modify the default generated "'DIRS': [os.path.join(BASE_DIR, 'templates')]", modify as follows: 'DIRS': [Path(
BASE_DIR , 'templates')]

3. Configure the mysql database

1. Install the mysql database locally

1) Install the mysql database

I am using 5.7.22 (my version), the installation is slightly

2) Create a database yourself

Create a database name: smalldjangodb

2. Install pymysql

pip install pymysql

3. Configure mysql database

1) Add in _init_.py under the same name package of the project

import pymysql
pymysql.install_as_MySQLdb()

 2) In the settings.py file, replace the content in DATABASES

 First comment out the default database configuration in the figure below

 Copy the following part in and modify it

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',#数据库的类型
'NAME': '', #所使用的的数据库的名字
'USER': 'root', #数据库服务器的用户
'PASSWORD': '', #密码
'HOST': '127.0.0.1', #主机
'PORT': '3306', #端口
}
}

4. Django default data migration

 1) Execute the migration, and migrate the original application model in the project to the database synchronously

pycharm's terminal input

python manage.py migrate

 2) View data migration results

5. Create a background super administrator 

pycharm's terminal input

python  manage.py createsuperuser

 Username, email (enter casually, the interface is in the correct format), password

The registration here is the super password qq+name abbreviation (a record for yourself)

 4. Log in to the background system

1. Start the service

python manage.py runserver

2. Log in to the background system

Use the super management account created in the previous step to log in to the system 

http://127.0.0.1:8000/admin

 Login success page:

5. Create an app application

1. Command to create an application

pycharm's terminal input

python  manage.py startapp lucky

 

 2. Configure the application in INSTALLED_APPS in settings

Add the application lucky to INSTALLED_APPS in the configuration settings

6. Configure application routing 

  

1. Configure the main route

 Create a sub-routing file urls.py under the application folder lucky

 Change it to the following picture:

 For multiple applications, configure multiple main routes

2. Configure sub-application routing

 Input (here views.toLoginView refers to the method toLoginView in views under the lucky application, which will be explained in the next step):

from django.urls import path
from . import views

urlpatterns = [
    path('', views.toLoginView, name='toLoginView'),
]

3. Configure views

Open the views under the lucky directory of the application

from django.shortcuts import render

# Create your views here.


def toLoginView(request):
    return render(request, 'login.html')

Seven, create html page

1. Determine whether the template configuration is correct

 2. Create a sample html page 

Create a login.html under templates

 8. Access

Start service access address: http://127.0.0.1:8000/lucky/

Open: settings.py open debug mode 
DEBUG = False 
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']

9. Optimize and implement simple get and post

1. Configure routing

from django.urls import path
from . import views

urlpatterns = [
    path('', views.toLoginView),
    path('index/', views.loginView),
]

2. Use the get method to realize

1) Configure the views page

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.


def toLoginView(request):
    return render(request, 'login.html')

def loginView(request):
    username = request.GET.get('user', '') # 后面的''表示获取不到user就赋值空
    password = request.GET.get('pwd', '')
    if username and password:
        return HttpResponse("登录成功")
    else:
        return HttpResponse("登录失败")

2) Optimize the login page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>

<form action="/lucky/index/" method="get">
    <p><label>用户名:</label><input name="user" /></p>
    <p><label>密码:</label><input name="pwd" /></p>
    <input type="submit" value="登录">

</form>


</body>
</html>

3) Display the results

Start service  http://127.0.0.1:8000/lucky/

 login successful

 The disadvantage of the get request is that the account password is exposed in the URL, so the post method will be explained below

3. Use the post method to realize

1) Configure the views page

from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.


def toLoginView(request):
    return render(request, 'login.html')

def loginView(request):
    username = request.POST.get('user', '') # 后面的''表示获取不到user就赋值空
    password = request.POST.get('pwd', '')
    # if username=='admin' and password=='1':
    if username and password:
        return HttpResponse("登录成功")
    else:
        return HttpResponse("登录失败")

2) Optimize the login page

Change the above get to post

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>

<form action="/lucky/index/" method="post">
    <p><label>用户名:</label><input name="user" /></p>
    <p><label>密码:</label><input name="pwd" /></p>
    <input type="submit" value="登录">

</form>


</body>
</html>

 3) Display the results

Start service  http://127.0.0.1:8000/lucky/

 10. Continue to optimize and use the database method for data judgment

1. Add the data model in model.py

from django.db import models

# Create your models here.

class UserInfo(models.Model):
    id = models.CharField(primary_key=True,max_length=20)
    name = models.CharField(max_length=20)
    password = models.CharField(max_length=20)

2. Migrate the data model to the database

Note that mysql must be able to support access at this time

python manage.py makemigrations lucky

 Migrate data to mysql database

python manage.py migrate

 To database verification:

 3. Create data for subsequent operations

 4. Modify views.py

from django.http import HttpResponse
from django.shortcuts import render
from .models import *

# Create your views here.


def toLoginView(request):
    return render(request, 'login.html')

def loginView(request):
    user_name = request.POST.get('user', '') # 后面的''表示获取不到user就赋值空
    pass_word = request.POST.get('pwd', '')
    # if user_name=='admin' and pass_word=='1':
    if user_name and pass_word:
        exit_user =UserInfo.objects.filter(name= user_name,password = pass_word).count()
        if exit_user >= 1:
            return HttpResponse("登录成功!")
        else:
            return HttpResponse("帐号密码错误!")
    else:
        return HttpResponse("请输入正确用户名和密码!")

5. Verification

 

11. Realize registration

1. Registration page

Create register.html under templates 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>

<form action="/lucky/register/" method="post">
    {% csrf_token %}
    <p><label>用户名:</label><input name="user" /></p>
    <p><label>密码:</label><input name="pwd" /></p>
    <input type="submit" value="注册">

</form>


</body>
</html>

2. Configure routing

from django.urls import path
from . import views

urlpatterns = [
    path('', views.toLoginView),
    path('index/', views.loginView),
    path('toregister/', views.toRegisterView),
    path('register/', views.registerView),
]

3. Create a registration method

Create the registerView method and toRegisterView method in the views.py file

from django.http import HttpResponse
from django.shortcuts import render
from .models import *

# Create your views here.


def toLoginView(request):
    return render(request, 'login.html')

def loginView(request):
    user_name = request.POST.get('user', '') # 后面的''表示获取不到user就赋值空
    pass_word = request.POST.get('pwd', '')
    # if user_name=='admin' and pass_word=='1':
    if user_name and pass_word:
        exit_user = UserInfo.objects.filter(name=user_name, password=pass_word).count()
        if exit_user >= 1:
            return HttpResponse("登录成功!")
        else:
            return HttpResponse("帐号密码错误!")
    else:
        return HttpResponse("请输入正确用户名和密码!")

# 渲染注册页面
def toRegisterView(request):
    return render(request, 'register.html')

# 注册的逻辑判断
def registerView(request):
    user_name = request.POST.get('user', '')
    pass_word = request.POST.get('pwd', '')
    if user_name and pass_word:
        register_user = UserInfo(name=user_name, password=pass_word)
        register_user.save()
        return HttpResponse("注册成功!")
    else:
        return HttpResponse("请输入完整的用户名和密码!")

 4. Access verification

Note that the application name should be added to the access path, which is related to the routing configuration

Visit  http://127.0.0.1:8000/lucky/toregister/

 registration success

 database validation

This is the registration plus a repeated judgment

# 注册的逻辑判断
def registerView(request):
    user_name = request.POST.get('user', '')
    pass_word = request.POST.get('pwd', '')
    if user_name and pass_word:
        exit_user = UserInfo.objects.filter(name=user_name).count()        
        if exit_user:
            return HttpResponse("对不起,当前账户已存在!请换一个id注册")
        else:
            register_user = UserInfo(name=user_name, password=pass_word)
            register_user.save()
            return HttpResponse("注册成功!")
    else:
        return HttpResponse("请输入完整的用户名和密码!")

12. Anti-mapping database tables to django models

This will map all the tables in the database

# lucky 是django的应用名
python manage.py inspectdb>lucky/models.py

Guess you like

Origin blog.csdn.net/legend818/article/details/129005072