栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

《Django开发从入门到实践》学习笔记(代码)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

《Django开发从入门到实践》学习笔记(代码)

代码情况 urls.py

C:CodeBookManagementBookManagementurls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('management.urls')),  # 将management应用的URL设置包含到项目的URL设置中
]

C:CodeBookManagementmanagementurls.py

from django.urls import URLPattern, path
from management import views
from django.views.generic import RedirectView

urlpatterns = [
    path('', views.index, name='homepage'),
    path('favicon.ico',RedirectView.as_view(url='/static/images/droplet-half.svg')),
    path('index/', views.index, name='homepage'),
    path('sign_up/', views.sign_up, name='sign_up'),
    path('login/', views.login, name='login'),
    path('logout/', views.logout, name='logout'),
    path('change_password/', views.change_password, name='change_password'),
    path('add_book/', views.add_book, name='add_book'),
    path('edit_book', views.edit_book, name='edit_book'),
    path('book_list', views.book_list, name='book_list'),
    path('error/', views.error, name='error'),
    path('add_category/', views.add_category, name='add_category'),
    path('edit_category', views.edit_category, name='edit_category'),
    path('category_list', views.category_list, name='category_list'),
    path('book_detail', views.book_detail, name='book_detail'),
]
models.py

C:CodeBookManagementmanagementmodels.py

from django.db import models

# Create your models here.

class Book(models.Model):
    name = models.CharField(max_length=128, verbose_name='书籍名称')
    author = models.CharField(max_length=64, blank=True, verbose_name='作者')
    describe = models.CharField(max_length=64, blank=True, verbose_name='描述')
    index = models.CharField(max_length=64, blank=True, verbose_name='目录')
    price = models.FloatField(default=0.0, verbose_name='定价')
    publish_date = models.DateField(null=True, blank=True, verbose_name='出版日期')
    category = models.CharField(
        max_length=32, default='未分类', verbose_name='分类'
    )
    create_datetime = models.DateTimeField(
        auto_now_add=True, verbose_name='添加日期'
    )  # auto_now_add参数自动填充当前时间

    def __str__(self):  # 定义__str__方法后,在将模型对象作为参数传递给str()函数时会调用该方法返回相应的字符串
        return self.name

class Category(models.Model):
    parent_category = models.CharField(max_length=32, null=True, blank=True, verbose_name="父类")
    category = models.CharField(
        max_length=32, verbose_name='分类'
    )
settings.py

C:CodeBookManagementBookManagementsettings.py

"""
Django settings for BookManagement project.

Generated by 'django-admin startproject' using Django 3.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*6g14r6ubexu1v_m(_$rzgucc+v^avme(0&yfpm56tvuh6(mov'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'management',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'BookManagement.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'BookManagement.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
views.py

C:CodeBookManagementmanagementviews.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.contrib.auth.models import User, auth
import email
from xml.etree.ElementTree import tostring
# Create your views here.

def index(request):
    if request.user.is_authenticated:
        content={
            'username':request.user,
        }
        return render(request, "management/index.html",content)
    return render(request, "management/index.html")

def sign_up(request):
    if request.method == "POST":
        try:
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            repassword = request.POST.get('repassword', '')
            email = request.POST.get('email', '')
            if password == '' or repassword == '':
                state = '口令都不填的么'
            elif password != repassword:
                state = '你这两遍口令填的不同啊'
            elif username == '':
                state = '用户名格式错误'
            elif email == '':
                state = '邮箱是要填的呦'
            else:
                if User.objects.filter(username=username):
                    state = '换个用户名,这个已经被占用了'
                else:
                    new_user = User.objects.create_user(
                        username=username, password=password, email=email)
                    new_user.save()
                    state = '注册成功'
                    user = auth.authenticate(username=username, password=password)
                    auth.login(request, user)
                    return redirect("https://blog.csdn.net/index/")
        except:
            state = '注册失败'
        finally:
            return HttpResponse(state)
    if request.user.is_authenticated:
        return redirect("/index")
    return render(request, "management/sign_up.html")

def login(request):
    if request.method == "POST":
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        if username and password:
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                auth.login(request, user)
                state = '登录成功'
            else:
                state = '用户不存在或口令错误'
        else:
            state = '请输入用户名和口令'
        return HttpResponse(state)
    if request.user.is_authenticated:
        return redirect("/index")
    return render(request, "management/login.html")


def logout(request):
    auth.logout(request)
    return redirect("https://blog.csdn.net/index/")


def change_password(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            user = request.user
            password = request.POST.get('password', '')
            newpassword = request.POST.get('newpassword', '')
            confirmpassword = request.POST.get('confirmpassword', '')
            if user.check_password(password):
                if not newpassword:
                    state = '新口令要填的呦'
                elif newpassword != confirmpassword:
                    state = '两次口令输入的不同呦'
                else:
                    user.set_password(newpassword)
                    user.save()
                    state = '修改成功'
            else:
                state = '口令输错了'
            return HttpResponse(state)
        content={
            'username':request.user,
        }
        return render(request, "management/change_password.html",content)
    return render(request, "management/change_password.html")

from management import models
import math

def book_list(request):
    if request.user.is_authenticated:
        if request.method == "GET":
            search=request.GET.get('search','')
            page=int(request.GET.get('page',1))
            book_list = models.Book.objects.filter(name__regex=search).only('id','name','author','publish_date','price')[(15*(page-1)):15*page-1]
            book_list_count = math.ceil(models.Book.objects.filter(name__regex=search).only('id').count()/15)
            lastpage = int(page-1)
            nextpage = int(page+1)
            if lastpage <= 0 :
                lastpage = 1 
            if nextpage > int(book_list_count):
                nextpage = int(book_list_count)
            content={
                'username':request.user,
                'book_list':book_list,
                'lastpage':lastpage,
                'nextpage':nextpage,
                'search':search,
            }
            return render(request,"managementhttps://blog.csdn.net/book_list.html",content)
    return render(request,"managementhttps://blog.csdn.net/book_list.html")

from management import models

def add_book(request):
    if request.user.is_authenticated:
        if request.method == "GET":
            category_list = models.Category.objects.all().only('category')
            content = {
                'username':request.user,
                'category_list':category_list,
            }
            return render(request,"management/add_book.html",content)
        if request.method == "POST":
            try:
                name = cleandata.TypeChar(request.POST.get('name', ''))
                author = cleandata.TypeChar(request.POST.get('author', ''))
                price = cleandata.TypeFloat(request.POST.get('price', ''))
                publish_date = cleandata.TypeDate(request.POST.get('publish_date', ''))
                category = cleandata.TypeChar(request.POST.get('category', ''))
                create_datetime = cleandata.TypeDatetime(request.POST.get('create_datetime', ''))
                if name == "":
                    state='书名都不填的么'
                elif author == "":
                    state='作者都不填的么'
                elif price == "":
                    state='价格都不填的么'
                elif publish_date == "":
                    state='出版日期都不填的么'
                elif category == "":
                    state='类型都不选的么'
                else:
                    if models.Book.objects.filter(name=name,author=author):
                        state='已经添加过这本书籍了'
                    else:
                        models.Book.objects.create(
                            name = name,
                            author = author,
                            price = price,
                            publish_date = publish_date,
                            category = category,
                            create_datetime = create_datetime,
                        )
                        state='添加成功'
            except:
                state='添加失败'
            finally:
                return HttpResponse(state)
    return render(request,"management/add_book.html")

def edit_book(request):
    if request.user.is_authenticated:
        if request.method == "GET":
            id = request.GET.get('id','')
            if id:
                book = models.Book.objects.get(id=id)
                category_list = models.Category.objects.all().only('category')
                content = {
                    'username':request.user,
                    'category_list':category_list,
                    'book':book,
                }
            else:
                return redirect("https://blog.csdn.net/add_book/")
            return render(request,"management/edit_book.html",content)
        elif request.method == "POST":
            try:
                id = request.POST.get('id', '')
                name = cleandata.TypeChar(request.POST.get('name', ''))
                author = cleandata.TypeChar(request.POST.get('author', ''))
                describe = cleandata.TypeChar(request.POST.get('describe', ''))
                index = cleandata.TypeChar(request.POST.get('index', ''))
                price = cleandata.TypeFloat(request.POST.get('price', ''))
                publish_date = cleandata.TypeDate(request.POST.get('publish_date', ''))
                category = cleandata.TypeChar(request.POST.get('category', ''))
                if name == "":
                    state='书名都不填的么'
                elif author == "":
                    state='作者都不填的么'
                elif price == "":
                    state='价格都不填的么'
                elif publish_date == "":
                    state='出版日期都不填的么'
                elif category == "":
                    state='类型都不选的么'
                else:
                    models.Book.objects.filter(id=id).update(
                        name = name,
                        author = author,
                        describe = describe,
                        index = index,
                        price = price,
                        publish_date = publish_date,
                        category = category,
                    )
                    state='编辑成功'
            except:
                state='编辑失败'
            finally:
                return HttpResponse(state)
    return render(request,"management/edit_book.html")

def error(request):
    return render(request,"error.html")

def add_category(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            try:
                parent_category = cleandata.TypeChar(request.POST.get('parent_category', ''))
                category = cleandata.TypeChar(request.POST.get('category',''))
                if category:
                    if models.Book.objects.filter(category=category):
                        state='已经添加过这个子类了'
                    else:
                        new_category = models.Category (
                            parent_category = parent_category,
                            category = category,
                        )
                        new_category.save()
                        state='添加成功'
                else:
                    state='子类没有填内容哦'
            except:
                state='添加失败'
            finally:
                return HttpResponse(state)
        category_list = models.Category.objects.all().only('category')
        content={
            'username':request.user,
            'category_list':category_list,
        }
        return render(request, "management/add_category.html",content)
    return render(request,"management/add_category.html")

def edit_category(request):
    if request.user.is_authenticated:
        if request.method == "GET":
            id = request.GET.get('id','')
            if id:
                category = models.Category.objects.get(id=id)
                category_list = models.Category.objects.all().only('category')
                content={
                    'username':request.user,
                    'category_list':category_list,
                    'category':category,
                }
            else:
                return redirect("https://blog.csdn.net/add_category/")
            return render(request,"management/edit_category.html",content)
        elif request.method == "POST":
            try:
                id = request.POST.get('id', '')
                parent_category = cleandata.TypeChar(request.POST.get('parent_category', ''))
                category = cleandata.TypeChar(request.POST.get('category',''))
                if category:
                    if models.Category.objects.filter(parent_category=parent_category,category=category):
                        state='已经添加过这个子类了'
                    else:
                        a=models.Category.objects.filter(id=id).update(parent_category=parent_category,category=category)
                        print("---------------------------------------")
                        print(a)
                        state='编辑成功'
                else:
                    state='子类没有填内容哦'
            except:
                state='编辑失败'
            finally:
                return HttpResponse(state)
        else:
            return redirect("/error/")

def category_list(request):
    if request.user.is_authenticated:
        if request.method == "GET":
            search=request.GET.get('search','')
            page=int(request.GET.get('page',1))
            category_list = models.Category.objects.filter(category__regex=search).only('id','parent_category','category')[(15*(page-1)):15*page-1]
            category_list_count =math.ceil(models.Category.objects.filter(category__contains=search).only('id').count()/15)
            lastpage = int(page-1)
            nextpage = int(page+1)
            if lastpage <= 0 :
                lastpage = 1 
            if nextpage > int(category_list_count):
                nextpage = int(category_list_count)
            content={
                'username':request.user,
                'category_list':category_list,
                'lastpage':lastpage,
                'nextpage':nextpage,
                'search':search,
            }
            return render(request,"managementhttps://blog.csdn.net/category_list.html",content)
    return render(request,"managementhttps://blog.csdn.net/category_list.html")
            
def book_detail(request):
    if request.user.is_authenticated:
        if request.method == "GET":
            id = cleandata.TypeNum(request.GET.get('id', ''))
            if id != '' and id != 0:
                book = models.Book.objects.get(id=id)
                content = {
                    'book':book,
                }
                return render(request,"management/book_detail.html",content)
    return render(request,"management/book_detail.html")

class cleandata():
    def TypeNum(data):
        try:
            return int(data)
        except:
            return int(0)
    
    def TypeFloat(data):
        try:
            return float(data)
        except:
            return float(0.00)

    def TypeEmail(data):
        try:
            return email(data)
        except:
            return email("@163.com")
    
    def TypeUsername(data):
        try:
            return tostring(data).replace(["'","<",">","#"],"")
        except:
            return None
    
    def TypeChar(data):
        try:
            return data.replace("'","")
        except:
            return None

    def TypeDate(data):
        try:
            return data
        except:
            return None
    
    def TypeDatetime(data):
        try:
            return data
        except:
            return None
templates add_book.html
{% extends "management/navbar.html" %}

{% block title %}添加书籍信息{% endblock %}

{% block content %}

添加书籍

{% csrf_token %}

{% endblock %} {% block javascript %} {% endblock %}
add_category.html

C:CodeBookManagementtemplatesmanagementadd_category.html

{% extends "management/navbar.html" %}

{% block title %}添加书籍分类{% endblock %}

{% block content %}


添加分类

{% csrf_token %}

{% endblock %} {% block javascript %} {% endblock %}
book_detail.html

C:CodeBookManagementtemplatesmanagementbook_detail.html

{% extends "management/navbar.html" %}

{% block title %}书籍详情{% endblock %}

{% block content %}


Heroes examples

{{book.name}}

作者:{{book.author}}

分类:{{book.category}}

简介:{{book.describe}}

价格:{{book.price}}

出版日期:{{book.publish_date}}

{% endblock %}
book_list.html

C:CodeBookManagementtemplatesmanagementbook_list.html

{% extends "management/navbar.html" %}

{% block title %}书籍列表{% endblock %}

{% block content %}


{% csrf_token %} {% for book in book_list %} {% endfor %}
# 书名 作者 出版日期 定价
{{forloop.counter}} {{book.name}} {{book.author}} {{book.publish_date}} {{book.price}} 编辑
{% endblock %} {% block javascript %} {% endblock %}
category_list.html

C:CodeBookManagementtemplatesmanagementcategory_list.html

{% extends "management/navbar.html" %}

{% block title %}书籍分类列表{% endblock %}

{% block content %}



{% csrf_token %} {% for category in category_list %} {% endfor %}
# 父类 分类
{{forloop.counter}} {{category.parent_category}} {{category.category}} 编辑
{% endblock %} {% block javascript %} {% endblock %}
change_password.html

C:CodeBookManagementtemplatesmanagementchange_password.html

{% extends "management/navbar.html" %}

{% block title %}修改口令{% endblock %}

{% block content %}

修改口令

{% csrf_token %}

Quick Quick Change Password.
{% endblock %} {% block javascript %} {% endblock %}
edit_book.html

C:CodeBookManagementtemplatesmanagementedit_book.html

{% extends "management/navbar.html" %}

{% block title %}编辑书籍信息{% endblock %}

{% block content %}

编辑图书

{% csrf_token %}

{% endblock %} {% block javascript %} {% endblock %}
edit_category.html

C:CodeBookManagementtemplatesmanagementedit_category.html

{% extends "management/navbar.html" %}

{% block title %}编辑书籍分类{% endblock %}

{% block content %}

编辑分类

{% csrf_token %}

{% endblock %} {% block javascript %} {% endblock %}
index.html

C:CodeBookManagementtemplatesmanagementindex.html

{% extends "management/navbar.html" %}

{% block title %}主页{% endblock %}

{% block content %}

欢迎使用图书管理系统

图书馆管理系统,能进行图书馆管理系统能实测国民经济和企业的各种运行情况;利用过去的数据预测未来;从企业全局出发辅助企业进行管理决策;利用信息控制企业的行为;帮助企业实现其规划目标。
图书馆管理系统合运用了管理科学,系统科学,运筹学,统计学,计算机科学等学科的知识。可以通俗的简化的描述图书馆管理系统的三要素:系统的观点、数学的方法以及计算机的应用。
图书馆管理系统概念结构主要由四大部分组成即信息源、信息处理器、信息用户、信息管理者组成。

{% endblock %}
login.html

C:CodeBookManagementtemplatesmanagementlogin.html

{% extends "management/navbar.html" %}

{% block title %}登录{% endblock %}

{% block content %}

欢迎登录图书管理系统

图书馆管理系统,能进行图书馆管理系统能实测国民经济和企业的各种运行情况;利用过去的数据预测未来;从企业全局出发辅助企业进行管理决策;利用信息控制企业的行为;帮助企业实现其规划目标。
图书馆管理系统合运用了管理科学,系统科学,运筹学,统计学,计算机科学等学科的知识。可以通俗的简化的描述图书馆管理系统的三要素:系统的观点、数学的方法以及计算机的应用。
图书馆管理系统概念结构主要由四大部分组成即信息源、信息处理器、信息用户、信息管理者组成。

{% csrf_token %}

By clicking Login, you agree to the terms of use.
{% endblock %} {% block javascript %} {% endblock %}
navbar.html

C:CodeBookManagementtemplatesmanagementnavbar.html

{% load static %}




  
  
  {% block title%}{% endblock %}
  
  
  


{% block content %} {% endblock %}

© 2022 Company, Inc. All rights reserved.

{% block javascript %} {% endblock %}
sign_up.html

C:CodeBookManagementtemplatesmanagementsign_up.html

{% extends "management/navbar.html" %}

{% block title %}注册{% endblock %}

{% block content %}

注册

{% csrf_token %}

By clicking Sign up, you agree to the terms of use.
{% endblock %} {% block javascript %} {% endblock %}
error.html

C:CodeBookManagementtemplateserror.html

{% extends "management/navbar.html" %}

{% block title %}404{% endblock %}

{% block content %}
    

给你一个错误自己领会

{% endblock %}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876153.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号