图书管理系统简单版

 

图书管理系统简单版_第1张图片

创建model 对象

models.py   

作者   作者详情    出版社     图书

from django.db import models


# Create your models here.

class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    authorDetail = models.OneToOneField("AuthorDetail")

    def __str__(self):
        return self.name


class AuthorDetail(models.Model):
    nid = models.AutoField(primary_key=True)
    birthday = models.DateField()
    telephone = models.CharField(max_length=11)
    addr = models.CharField(max_length=64)


class Publish(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    city = models.CharField(max_length=32)
    email = models.EmailField()

    def __str__(self):
        return self.name


class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    publishDate = models.DateField()
    publish = models.ForeignKey("Publish")
    authors = models.ManyToManyField("Author")

    def __str__(self):
        return self.title

数据库创建一些数据 create_bluk

import os

if __name__ == '__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tushu.settings")
    import django

    django.setup()
    from app01 import models
    import random

    l1 = []
    for i in range(1, 101):
        obj = models.Book(
            title='哈哈%s' % i,
            # price=1+i,
            publishDate='2018-01-0%s' % (random.randint(1, 9)),
            publish_id=random.randint(1, 3),
        )
        l1.append(obj)
    models.Book.objects.bulk_create(l1)

from.py 样式

from django import forms
from app01 import models


class MyForm(forms.Form):
    title = forms.CharField(
        max_length=32,
        min_length=2,
        error_messages={
            "required": "内容不能为空",
            "min_length": "长度不能小于2位",
            "max_length": "长度不能大于32位",
        },
        label="书名",
    )
    publishDate = forms.DateField(
        label="出版日期",
        widget=forms.widgets.DateInput(attrs={"type": "date"})
    )
    publish = forms.ModelChoiceField(
        label="出版社",
        queryset=models.Publish.objects.all(),
        widget=forms.widgets.Select()
    )
    authors = forms.ModelMultipleChoiceField(
        label="作者",
        queryset=models.Author.objects.all(),
        widget=forms.widgets.SelectMultiple()
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs.update({
                "class": "form-control",
                # "error_messages": {
                #     "required": "内容不能为空",
                # },
            }
            )

视图  view

from django.shortcuts import render, HttpResponse, redirect

# Create your views here.
from app01 import models
from form.form import MyForm
from django.http import JsonResponse


def show(request):
    all_books = models.Book.objects.all()
    return render(request, "show.html", {"all_books": all_books})


def create_book(request):
    if request.method == "GET":
        form_obj = MyForm()
        return render(request, "create_book.html", {"form_obj": form_obj})
    else:
        data = request.POST
        form_obj = MyForm(data)
        if form_obj.is_valid():
            data = form_obj.cleaned_data
            author_data = data.pop('authors')
            book_obj = models.Book.objects.create(**data)
            book_obj.authors.add(*author_data)
            return redirect("show")
        else:
            return render(request, "create_book.html", {"form_obj": form_obj})


def editor_book(request, n):
    book_obj = models.Book.objects.filter(pk=n)
    if request.method == "GET":
        book_obj = book_obj.first()
        all_publish = models.Publish.objects.all()
        all_authors = models.Author.objects.all()
        return render(request, 'editor_book.html',
                      {"n": n, "book_obj": book_obj, "all_publish": all_publish, "all_authors": all_authors})

    else:
        data = request.POST.dict()
        author_data = request.POST.getlist("authors")
        print(data, "++++++++++++++")
        print(author_data)
        # print(author_data['authors'],'----------------')
        del data["csrfmiddlewaretoken"]
        data.pop("authors")
        book_obj.update(**data)
        book_obj[0].authors.set(author_data)
        return redirect("show")


def delete_book(request, n):
    models.Book.objects.filter(pk=n).delete()
    return redirect("show")


def ajax_delete_book(request, n):
    data = {"status": False}
    if request.method == "POST":
        models.Book.objects.filter(pk=n).delete()
        data["status"] = True
        return JsonResponse(data)
    else:
        return JsonResponse(data)


    # try:
    #     data['status'] = 1
    #     models.Book.objects.filter(pk=n).delete()
    # except Exception:
    #     data['status'] = 2
    # return JsonResponse(data)

 

html 页面

show.html

{% load static %}

"en">

    "UTF-8">
    show
    "stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">


书籍展示

class="container-fluid">
class="row">
class="col-md-8 col-md-offset-2"> class="btn btn-primary" href="{% url 'create_book' %}">添加书籍 class="table table-bordered table-striped table-hover"> {% for book in all_books %} {% endfor %}
序号 书名 出版日期 出版社 作者 操作
{{ forloop.counter }} {{ book.title }} {{ book.publishDate|date:"Y-m-d" }} {{ book.publish.name }} {% for author in book.authors.all %} {{ author.name }} {% if forloop.last %} {% else %} , {% endif %} {% endfor %} "{% url 'editor_book' book.pk %}" class="btn btn-warning">编辑 "{% url 'delete_book' book.pk %} " class="btn btn-danger">删除 class="hidden">{{ book.pk }}

 

create_book.html

{% load static %}

"en">

    "UTF-8">
    show
    "stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">


添加书籍

class="container-fluid">
class="row">
class="col-md-8 col-md-offset-2"> {#form表单#}
"{% url 'create_book' %}" method="post" novalidate> {% csrf_token %} {% for field in form_obj %}
class="form-group {% if field.errors.0 %} has-error {% endif %} "> {{ field }} class="text-danger">{{ field.errors.0 }}
{% endfor %} "submit" class="btn btn-success pull-right" value="保存">

editor_book.html

{% load static %}

"en">

    "UTF-8">
    show
    "stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">


添加书籍

class="container-fluid">
class="row">
class="col-md-8 col-md-offset-2"> {#form表单#}
"{% url 'create_book' %}" method="post" novalidate> {% csrf_token %} {% for field in form_obj %}
class="form-group {% if field.errors.0 %} has-error {% endif %} "> {{ field }} class="text-danger">{{ field.errors.0 }}
{% endfor %} "submit" class="btn btn-success pull-right" value="保存">

 

图书管理系统简单版_第2张图片

 

 图书管理系统简单版_第3张图片

图书管理系统简单版_第4张图片

 

转载于:https://www.cnblogs.com/XLHIT/p/11217137.html

你可能感兴趣的:(python,javascript,数据库)