React small project-online calculator (Part 2)

This article is the next part of the React project (online calculator), which is mainly about the development of the back-end part. The previous part can be found: React small project-online calculator (Part 1) .

1. Django project initialization

We first open a terminal in the project root directory and create a Python virtual environment:

python -m venv venv

Start the virtual environment:

.\venv\Scripts\Activate.ps1

Installation Environment:

pip install django
npm i jquery

Check Django version:

django-admin --version

Create a Django project:

django-admin startproject calculator_django

Synchronize database modifications:

python manage.py migrate

Start the Django project:

python manage.py runserver localhost:8000

Create an admin user (assuming username and password are both admin):

python manage.py createsuperuser

Create a new App:

python manage.py startapp app

Delete and appin the directory , create , , folders, and create files in these three directories.views.pymodels.pyviewsmodelsurls__init__.py

Update the total URL file ( calculator_django/calculator_django/urls.py):

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('app.urls.index')),
    path('admin/', admin.site.urls),
]

Then make some global settings for the project. First, set the time zone of the project, open it calculator_django/calculator_django/settings.py(all subsequent operations are in this file), and modify TIME_ZONE:

TIME_ZONE = 'Asia/Shanghai'

To prevent cross-domain issues, we can add the following line of code:

SECURE_CROSS_ORIGIN_OPENER_POLICY = 'None'

Then load the App you created, find it INSTALLED_APPS, and app/apps.pyadd it:

INSTALLED_APPS = [
    'app.apps.AppConfig',  # 添加此行
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Find STATIC_URL = 'static/', add a few lines near it:

import os  # 在文件首部导入包

STATIC_ROOT = os.path.join(BASE_DIR, 'static')  # 表示要将静态文件放到static目录下
STATIC_URL = 'static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'media/'

We appcreate statica folder in the directory and then http://localhost:8000/static/xxxaccess staticthe static files in the directory through links.

2. Login/registration backend function implementation

We calculator_django/app/viewscreate it in the directory login.py:

from django.contrib.auth import authenticate, login
from django.http import JsonResponse

def mylogin(request):
    data = request.GET
    username = data.get('username')
    password = data.get('password')
    user = authenticate(username=username, password=password)
    if not user:
        return JsonResponse({
   
    
    
            'result': 'Username or password wrong!',

        })
    login(request, user)
    return JsonResponse({
   
    
    
        'result': 'success',
    })

Then create logout.py:

from django.contrib.auth import logout
from django.http import JsonResponse

def mylogout(request):
    user = request.user
    if not user.is_authenticated:
        return JsonResponse({
   
    
    
            'result': 'success',
        })
    logout(request)
    return JsonResponse({
   
    
    
        'result': 'success',
    })

Then create register.py:

from django.contrib.auth import login
from django.contrib.auth.models import User
from django.http import JsonResponse

def register(request):
    data = request.GET
    username = data.get('username', '').strip()  # 如果没有的话返回空,且过滤掉空格
    password = data.get('password', '').strip()
    confirm_password = data.get('confirm_password', '').strip()
    if not username or not password:  # 用户名或密码为空
        return JsonResponse({
   
    
    
            'result': 'Username or password can\'t be empty!',
        })
    elif password != confirm_password:  # 两次密码不一致
        return JsonResponse({
   
    
    
            'result': 'Password inconsistency!'
        })
    elif User.objects.filter(username=username).exists():  # 用户名已存在
        return JsonResponse({
   
    
    
            'result': 'Username has existed!'
        })
    user = User(username=username)
    user.set_password(password)
    user.save()
    login(request, user)
    return JsonResponse({
   
    
    
        'result': 'success',
    })

Now calculator_django/app/urlswrite the route in the directory index.py:

from django.urls import path
from app.views.login import mylogin
from app.views.logout import mylogout
from app.views.register import register

urlpatterns = [
    path('login/', mylogin, name='login'),
    path('logout/', mylogout, name='logout'),
    path('register/', register, name='register'),
]

3. Login/registration front-end interface design

Now we implement the login interface ( login.jsxfile):

import React, {
   
    
     Component } from 'react';
import Card from './card';
import $ from 'jquery';

class Login extends Component {
   
    
    
    state = {
   
    
    
        username: '',
        password: '',
        error_message: '',  // 错误信息提示
    };

    handleLogin = (e) => {
   
    
    
        e.preventDefault();  // 阻止默认的提交行为,之后用ajax提交
        this.setState({
   
    
    error_message: 

Guess you like

Origin blog.csdn.net/m0_51755720/article/details/132855932