mybook Django项目

数据库mybook
项目 mybook
app bookstore & userinfo
django-admin startproject mybook
python manage.py startapp bookstore

templates文件中index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
{% csrf_token %}
<p>
    <a href="/bookstore/add">添加图书</a>
</p>
<p>
    <a href="/bookstore/list_all">查看图书</a>
</p>
</body>
</html>

list_all.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>显示图书</title>
</head>
<a href="/bookstore/add">返回添加图书页面</a>
<form action="/bookstore/search" method="get">
    <input type="text" name="search">
    <input type="submit" value="搜索">
</form>
<body>
<form action="/bookstore/list_all">
{% csrf_token %}
    <table>
        <tr>
            <th>书名</th>
            <th>出版社</th>
            <th>阅读量</th>
            <th>评论量</th>
            <th>修改</th>
            <th>删除</th>
        </tr>
        {% for i in abook %}
            <tr>
                <td>{{ i.title }}</td>
                <td>{{ i.pub_house }}</td>
                <td>{{ i.read }}</td>
                <td>{{ i.comment }}</td>
                <td><a href="mod/{{ i.id }}">修改</a></td>
                <td><a href="del/{{ i.id }}">删除</a></td>
            </tr>
        {% endfor %}
        {% for i in all_book %}
            <tr>
                <td>{{ i.title }}</td>
                <td>{{ i.pub_house }}</td>
                <td>{{ i.read }}</td>
                <td>{{ i.comment }}</td>
                <td><a href="mod/{{ i.id }}">修改</a></td>
                <td><a href="del/{{ i.id }}">删除</a></td>
            </tr>
        {% endfor %}
    </table>

</form>
</body>
</html>

mod.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/bookstore/mod/{{ abook.id }}" method="post">
    {% csrf_token %}
    <div>
        书名:{{ abook.title }}
    </div>
    <div>
        <input type="text" name="pub_house" value="{{ abook.pub_house }}" placeholder="出版社">
    </div>
    <div>
        阅读量:{{ abook.read }}
    </div>
    <div>
        评论量:{{ abook.comment }}
    </div>
    <div>
        <input type="submit" value="修改">
    </div>
</form>
</body>
</html>

new_book.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<a href="/bookstore">返回首页</a>
<body>
<form action="/bookstore/add" method="post">
    {% csrf_token %}
    <div>
        <input type="text" name="title" required placeholder="书名">
    </div>
    <div>
        <input type="text" name="pub_house" required placeholder="出版社">
    </div>
    <div>
        <input type="text" name="read" required placeholder="阅读量">
    </div>
    <div>
        <input type="text" name="comment" required placeholder="评论量">
    </div>
    <div>
        <input type="submit" value="提交">

    </div>

</form>
</body>
</html>

mybook 文件夹中urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('bookstore/', include('bookstore.urls')),
    path('userinfo/', include('userinfo.urls'))
]

setting.py

"""
Django settings for mybook project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-9edh36k+!c-2zga=0d6e_b2fqre7)771@ae+7z!686uu*)6!--'

# 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',
    'bookstore',
    'userinfo'
]

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 = 'mybook.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 = 'mybook.wsgi.application'

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

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

# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

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

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

init.py

import pymysql
pymysql.install_as_MySQLdb()

bookstore APP文件中models.py

from django.db import models


# Create your models here.


class Book(models.Model):
    title = models.CharField('书名', max_length=50, default='untitled')
    pub_house = models.CharField('出版社', max_length=100)
    read = models.CharField('阅读量', max_length=2000)
    comment = models.CharField('评论量', max_length=255)

urls.py

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

urlpatterns = [

    path('', views.homepage),
    path('add', views.new_book),
    path('list_all', views.all_book),
    path('mod/<int:i_id>', views.mod),
    path('del/<int:i_id>', views.delete),
    path('search', views.search)
]

views.py

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

from . import models


# Create your views here.


def homepage(request):
    return render(request, 'index.html')


def new_book(request):
    if 'username' not in request.session:
        return render(request, 'login.html')
    if request.method == 'GET':
        return render(request, 'new_book.html')
    elif request.method == 'POST':
        title = request.POST.get('title', '')
        pub_house = request.POST.get('pub_house', '')
        read = request.POST.get('read', '')
        comment = request.POST.get('comment', '')
        mybook = models.Book.objects.create(
            title=title,
            pub_house=pub_house,
            read=read,
            comment=comment
        )
        return HttpResponse('<a href="/bookstore/add">添加成功,返回</a>')


def all_book(request):
    abook = models.Book.objects.all()
    return render(request, 'list_all.html', locals())


def mod(request, i_id):
    try:
        abook = models.Book.objects.get(id=i_id)
    except:
        return HttpResponse('没有找到id为:' + i_id + '的书籍')

    if request.method == 'GET':
        return render(request, 'mod.html', locals())
    elif request.method == 'POST':
        try:
            pub_house = request.POST.get('pub_house', 'xxx')
            abook.pub_house = pub_house
            abook.save()
            return HttpResponse('<a href="/bookstore">修改成功,返回首页</a>')
        except:
            return HttpResponse('修改失败')


def delete(request, i_id):
    try:
        abook = models.Book.objects.get(id=i_id)
        abook.delete()
        return HttpResponseRedirect('/bookstore/list_all')
    except:
        return HttpResponse('没有找到id为:' + i_id + "的书籍")


def search(request):
    title = request.GET.get('search')
    all_book = models.Book.objects.filter(title__contains=title)
    return render(request, 'list_all.html', locals())



userinfo文件中templates文件 中login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/userinfo/login" method="post">
    {% csrf_token %}
    <div>
        <lable>用户名</lable>
        <input type="text" name="username">
        {{ username.error }}
    </div>
    <div>
        <lable>密码</lable>
        <input type="password" name="password">
    </div>
    <div>
        <lable>记住密码</lable>
        <input type="checkbox" value="1" name="remember">
    </div>
    <div>
        <input type="submit" value="登录">
    </div>
</form>
</body>
</html>

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/userinfo/register" method="post">
    {% csrf_token %}
    <div>
        <lable>用户名</lable>
        <input type="text" name="username">
        <span>{{ username.error }}</span>
    </div>
    <div>
        <lable>密码</lable>
        <input type="password" name="password">
        {{ password.error }}
    </div>
    <div>
        <lable>确认密码</lable>
        <input type="password" name="password1">
    </div>
    <div>
        <input type="submit" value="提交">
    </div>
</form>
</body>
</html>

urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('login', views.login),
    path('register', views.register)

]

views.py

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


# Create your views here.
def login(request):
    if request.method == 'GET':
        username = request.COOKIES.get('username', '')
        return render(request, 'login.html', locals())
    elif request.method == 'POST':
        username = request.POST.get('username', '')
        remember = request.POST.get('remember', '')
        password = request.POST.get('password', '')

        try:
            user = models.User.objects.get(name=username,
                                           password=password)
            request.session['username'] = {
                "username": user.name,
                "id": user.id

            }

            return HttpResponse('<a href="/bookstore/add">登录成功,返回添加图书页面</a>')
        except:
            return HttpResponse('登录失败')


def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        password1 = request.POST.get('password1', '')
        if username == '':
            username.error = '用户名不能为空'
            return render(request, 'register.html', locals())
        elif password == '':
            password.error = '密码不能为空'
            return render(request, 'register.html', locals())
        elif password != password1:
            return HttpResponse('两次密码不一致')
        try:
            user = models.User.objects.create(
                name=username,
                password=password
            )
            return HttpResponse('注册成功')
        except:
            return HttpResponse('注册失败')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值