首页 > 其他 > 详细

Django学习笔记2

时间:2018-10-26 18:52:55      阅读:116      评论:0      收藏:0      [点我收藏+]

Django第一个简易项目理解框架

在理解了Django框架的基本目录结构之后,为了更好的理解框架的流程,我们通过一个简易项目来实践一下,上面的目录可总结为:在templates文件夹中写前端页面,在settings中进行Django基本配置,在app下的models中写数据库相关,在url中写路径的对应关系,在views中写请求处理。

下面的项目就对这些文件一个个进行书写。

配置相关

首先是各种配置的书写,一下都是在setting文件中的配置

1、理解settings文件中的BASE_DIR

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

这句话是获取项目的根路径,后面会用到。

2、在最初的时候先禁用csrf相关

MIDDLEWARE = [
‘django.middleware.security.SecurityMiddleware‘,
‘django.contrib.sessions.middleware.SessionMiddleware‘,
‘django.middleware.common.CommonMiddleware‘,
# ‘django.middleware.csrf.CsrfViewMiddleware‘, 在此禁用,一般在setting中的47行左右
‘django.contrib.auth.middleware.AuthenticationMiddleware‘,
‘django.contrib.messages.middleware.MessageMiddleware‘,
‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,
]

3、确认APP是否注册

如果是在pycharm中创建的APP,一般都会在setting文件中自动注册,格式如下,如果没有请手动添加

INSTALLED_APPS = [
‘django.contrib.admin‘,
‘django.contrib.auth‘,
‘django.contrib.contenttypes‘,
‘django.contrib.sessions‘,
‘django.contrib.messages‘,
‘django.contrib.staticfiles‘,
‘book_system.apps.BookSystemConfig‘, # 这行是app的注册语句 book_system是app名
]

4、配置template文件夹的位置

TEMPLATES = [
{
‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)] # 在此处配置,该DIRS是一个列表,可以配置多个
,
‘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‘,
],
},
},
]

5、配置静态文件存放的位置(本篇可不用此设置)

# 静态文件保存目录的别名
STATIC_URL = ‘/static/‘

# 所有静态文件(css/js/图片)都放在我下面你配置的文件夹中,同样是列表,路径可以多个
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]

6、配置数据库相关

这里编者是用的mysql数据库,然后连接的数据库名字为‘booksystem‘,

第一步------在settings文件中写下如下配置,先将原DATABASE注释掉

DATABASES = {
‘default‘: {
‘ENGINE‘: ‘django.db.backends.mysql‘,
‘NAME‘: ‘booksystem‘, # 数据库的名字
‘HOST‘: ‘127.0.0.1‘,
‘PORT‘: 3306,
‘USER‘: ‘root‘, # mysql数据库的用户名
‘PASSWORD‘: ‘root‘, # 密码
}
}

第二步------告诉Django用pymysql代替默认的MySQLDB 连接MySQL数据库

在项目/__init__.py文件中,写下面两句:
import pymysql
# 告诉Django用pymysql来代替默认的MySQLdb
pymysql.install_as_MySQLdb()

恭喜你,至此你的配置环节已经结束

数据库和models表的建立

1、自己动手创建数据库
create database booksystem;

2、在创建的APP目录下的models.py下写下如下类,可在创建的空数据库中创建一系列的表

from django.db import models


# Create your models here.


# 出版社类
class Publisher(models.Model):
    id = models.AutoField(primary_key=True)  # 自增的ID主键
    # 创建一个varchar(64)的唯一的不为空的字段
    name = models.CharField(max_length=64, null=False, unique=True)

    def __str__(self):
        return "<Author object>: {}".format(self.name)


# 书类
class Book(models.Model):
    id = models.AutoField(primary_key=True)
    # 创建一个varchar(64)的唯一的不为空的字段
    tittle = models.CharField(max_length=64, null=False, unique=True)
    # 和出版者关联的外键字段
    publisher = models.ForeignKey(to="Publisher")  # 设置书籍连接到出版者的外键
    # 数据库自动生成的外键会自动加上_id

    def __str__(self):
        return "<Author object>: {}".format(self.tittle)


# 作者类
class Author(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16, null=False, unique=True)
    book = models.ManyToManyField(to="Book")  # 创建作者表和书籍表多对多的关系
    # 多对多的关系会在数据库中另创建一个新的对应关系表,只存放id的对应关系

    def __str__(self):
        return "<Author object>: {}".format(self.name)

3、使创建的表结构通过django命令映射到数据库

(1). python manage.py makemigrations --> 把models.py里面的更改记录到小本本(相应APP的migrations文件夹下)
(2). python manage.py migrate              --> 把更改翻译成SQL语句,去数据库执行、

如果在pycharm环境中可以选择Tools-->Run manage.py task,然后会在下方弹出如下界面

技术分享图片

在后面输入makemigration [appname]和migrate [appname]可以达到和如上一样的结果,执行完毕会在对应的数据库下创建各种表

3、自动创建的数据表在数据库中的结构如下

技术分享图片

四个主要的表结构如下所示

技术分享图片

到这,数据库结构的创建已经结束,向表中填写数据即可使用

url的路径关系及处理函数

1、数据库构建完成后,我们着手于对访问地址的解析,写url的路径关系

技术分享图片
"""bookdjango URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r‘^$‘, views.home, name=‘home‘)
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r‘^$‘, Home.as_view(), name=‘home‘)
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r‘^blog/‘, include(‘blog.urls‘))
"""
from django.conf.urls import url
from django.contrib import admin
from book_system import views


urlpatterns = [
    url(r^admin/, admin.site.urls),

    # 出版社的对应关系
    url(r^publisher_list/, views.publisher_list),
    url(r^add_publisher/, views.add_publisher),
    url(r^delete_publisher/, views.delete_publisher),
    url(r^edit_publisher/, views.edit_publisher),

    # 书的对应关系
    url(r^book_list/, views.book_list),
    url(r^add_book/, views.add_book),
    url(r^delete_book/, views.delete_book),
    url(r^edit_book/, views.edit_book),

    # 作者的对应关系
    url(r^author_list/, views.author_list),
    url(r^add_author/, views.add_author),
    url(r^delete_author/, views.delete_author),
    url(r^edit_author/, views.edit_author),

    url(r^author_list1/, views.author_list1),

]
与项目目录同名的目录下的urls文件中代码

url函数的第一个参数为正则表达式,匹配接收的网址路径,匹配上了就交给后面第二个参数的函数处理

我们这里的函数写在了APP目录下的views模块里,也就是book_system中,根据需要把import那一行导入改成自己的APP

2、有了路径解析函数,下面写请求处理函数

在book_system下的views.py中写下路径处理函数

技术分享图片
from django.shortcuts import render, redirect, HttpResponse
from book_system import models


# Create your views here.


def publisher_list(request):
    # 去数据库查出所有的出版社,填充到html中,给用户界面
    ret = models.Publisher.objects.all().order_by("id")
    return render(request, "publisher_list.html", {"publisher_list": ret})


def add_publisher(request):
    error_msg = ""
    if request.method == "POST":
        new_name = request.POST.get("publisher_name")
        if new_name:
            models.Publisher.objects.create(name=new_name)
            return redirect("/publisher_list/")
        else:
            error_msg = "出版社的名字不能为空"
    return render(request, "add_publisher.html", {"error": error_msg})


def delete_publisher(request):
    del_id = request.GET.get("id")

    if del_id:
        del_obj = models.Publisher.objects.get(id=del_id)  # 这里的id相当于where语句
        del_obj.delete()
        return redirect("/publisher_list/")
    else:
        return HttpResponse("您要删除的数据不存在")


def edit_publisher(request):
    if request.method == "POST":
        publisher_id = request.POST.get("id")
        publisher_name = request.POST.get("publisher_name")

        publisher = models.Publisher.objects.get(id=publisher_id)
        publisher.name = publisher_name
        publisher.save()

        return redirect("/publisher_list/")
    else:
        edit_id = request.GET.get("id")
        print(models.Publisher.objects)
        edit_obj = models.Publisher.objects.get(id=edit_id)
        return render(request, "edit_publisher.html", {"edit_obj": edit_obj})


# book的相关试图操作
def book_list(request):
    # 去数据库查出所有的书籍,填充到html中,给用户界面
    ret = models.Book.objects.all().order_by("id")
    return render(request, "book_list.html", {"book_list": ret})


def add_book(request):
    error_msg = ""
    ret = models.Publisher.objects.all()
    if request.method == "POST":
        new_name = request.POST.get("book_name")
        new_publisher_id = request.POST.get("publisher")
        if new_name:
            models.Book.objects.create(tittle=new_name, publisher_id=new_publisher_id)
            return redirect("/book_list/")
        else:
            error_msg = "书本的名字不能为空"
    return render(request, "add_book.html", {
        "error": error_msg,
        "publisher_list": ret
    })


def delete_book(request):
    del_id = request.GET.get("id")

    if del_id:
        del_obj = models.Book.objects.get(id=del_id)  # 这里的id相当于where语句
        del_obj.delete()
        return redirect("/book_list/")
    else:
        return HttpResponse("您要删除的数据不存在")


def edit_book(request):
    ret = models.Publisher.objects.all()
    if request.method == "POST":
        book_id = request.POST.get("id")
        book_tittle = request.POST.get("book_tittle")
        book_publisher_id = request.POST.get("publisher")

        book = models.Book.objects.get(id=book_id)
        book.tittle = book_tittle
        book.publisher_id = book_publisher_id
        book.save()

        return redirect("/book_list/")
    else:
        edit_id = request.GET.get("id")
        print(models.Book.objects)
        edit_obj = models.Book.objects.get(id=edit_id)
        return render(request, "edit_book.html", {
            "edit_obj": edit_obj,
            "publisher_list": ret
        })


def author_list(request):
    all_author = models.Author.objects.all()
    return render(request, "author_list.html", {"author_list": all_author})


def add_author(request):
    error_msg = ""
    ret = models.Book.objects.all()
    if request.method == "POST":
        new_name = request.POST.get("author_name")
        new_books_id = request.POST.getlist("books")
        if new_name:
            new_book_obj = models.Author.objects.create(name=new_name)
            new_book_obj.book.set(new_books_id)  # 自动保存,不用save
            return redirect("/author_list/")
        else:
            error_msg = "作者的名字不能为空"
    return render(request, "add_author.html", {
        "error": error_msg,
        "book_list": ret
    })


def delete_author(request):
    del_id = request.GET.get("id")

    if del_id:
        models.Author.objects.get(id=del_id).delete()  # 这里的id相当于where语句
        return redirect("/author_list/")
    else:
        return HttpResponse("您要删除的数据不存在")


def edit_author(request):
    if request.method == "POST":
        old_id = request.POST.get("author_id")
        old_obj = models.Author.objects.get(id=old_id)

        new_name = request.POST.get("author_name")
        new_books_id = request.POST.getlist("books")
        print(new_books_id)

        # 更新
        old_obj.name = new_name
        old_obj.book.set(new_books_id)  # 自动保存,不用save
        old_obj.save()
        return redirect("/author_list/")

    edit_author_id = request.GET.get("id")
    edit_author_obj = models.Author.objects.get(id=edit_author_id)

    ret = models.Book.objects.all()

    return render(request, "edit_author.html", {
        "author": edit_author_obj,
        "book_list": ret,
    })


def author_list1(request):
    return render(request, "author_list1.html")
APP目录下的views.py中的代码

有了路径处理函数还远远不够,还需要html文件来配合显示

3、一下文件再都存放在项目根目录下的templates目录下

技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加作者</title>
</head>
<body>
<h1>添加作者信息</h1>
<form action="/add_author/" method="post">
    <p>
        姓名:<input type="text" name="author_name">
    </p>
    <p>
        著作:
        <select multiple name="books">
            {% for book in book_list %}
                <option value="{{ book.id }}">{{ book.tittle }}</option>
            {% endfor %}
        </select>
    </p>
    <input type="submit" value="提交">
    <p style="color: red;">{{ error }}</p>
</form>
</body>
</html>
add_author.html
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加书籍</title>
</head>
<body>
<h1>添加书籍信息</h1>
<form action="/add_book/" method="post">
    <p>
        书名:<input type="text" name="book_name">
    </p>
    <p>
        <select name="publisher">
            {% for publisher in publisher_list %}
                <option value="{{ publisher.id }}">{{ publisher.name }}</option>
            {% endfor %}
        </select>
    </p>
    <input type="submit" value="提交">
    <p style="color: red;">{{ error }}</p>
</form>
</body>
</html>
add_book.html
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>添加出版社</h1>
<form action="/add_publisher/" method="post">
    <input type="text" name="publisher_name">
    <input type="submit" value="提交">
    <p style="color: red;">{{ error }}</p>
</form>
</body>
</html>
add_publisher.html
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>作者列表</title>
</head>
<body>
{# a标签指向的位置找的也是urls.py文件中的对应关系的key。并不是直接找同级目录下的文件#}
<a href="/add_author/">添加新的作者信息</a>
<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>作品</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbady>
        {% for author in author_list %}
            <tr>
                <td>{{ author.id }}</td>
                <td>{{ author.name }}</td>
                <td>
                    {% for book in author.book.all %}
                        {{ book.tittle }}&nbsp;
                    {% endfor %}
                </td>
                <td>
                    <a href="/delete_author/?id={{ author.id }}">删除</a>
                    <a href="/edit_author/?id={{ author.id }}">编辑</a>
                </td>
            </tr>
        {% endfor %}
    </tbady>
</table>
</body>
</html>
author_list.html
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍列表</title>
</head>
<body>
{# a标签指向的位置找的也是urls.py文件中的对应关系的key。并不是直接找同级目录下的文件#}
<a href="/add_book/">添加新的书籍信息</a>
<table border="1">
    <thead>
    <tr>
        <th>ID</th>
        <th>书名</th>
        <th>出版社名称</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbady>
        {% for book in book_list %}
            <tr>
                <td>{{ book.id }}</td>
                <td>{{ book.tittle }}</td>
                <td>{{ book.publisher.name }}</td>
                <td>
                    <a href="/delete_book/?id={{ book.id }}">删除</a>
                    <a href="/edit_book/?id={{ book.id }}">编辑</a>
                </td>
            </tr>
        {% endfor %}
    </tbady>
</table>
</body>
</html>
book_list.html
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑作者</title>
</head>
<body>
<h1>编辑作者信息</h1>
<form action="/edit_author/" method="post">
    <input type="text" name="author_id" value="{{ author.id }}" style="display: none">
{{ author.id }}
    <p>
        姓名:<input type="text" name="author_name" value="{{ author.name }}">
    </p>
    <p>
        著作:
        <select multiple name="books">
            {% for book in book_list %}
                {% if book in author.book.all %}
                    <option selected value="{{ book.id }}">{{ book.tittle }}</option>
                {% else %}
                    <option value="{{ book.id }}">{{ book.tittle }}</option>
                {% endif %}
            {% endfor %}
        </select>
    </p>
    <input type="submit" value="提交">
    <p style="color: red;">{{ error }}</p>
</form>
</body>
</html>
edit_author.html
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑书籍信息</title>
</head>
<body>
<h1>编辑书籍信息</h1>
<form action="/edit_book/" method="post">
    <input type="text" name="id" value="{{ edit_obj.id }}" style="display: none;">
    <p>
        <input type="text" name="book_tittle" value="{{ edit_obj.tittle }}">

    </p>
    {#    <input type="text" name="publisher_name" value="{{ edit_obj.name }}">#}
    <p>
        <select name="publisher">
            {% for publisher in publisher_list %}
                {% if edit_obj.publisher_id == publisher.id %}
                    <option selected value="{{ publisher.id }}">{{ publisher.name }}</option>
                {% else %}
                    <option value="{{ publisher.id }}">{{ publisher.name }}</option>
                {% endif %}
            {% endfor %}
        </select>
    </p>
    <input type="submit" value="提交">
    <p style="color: red;">{{ error }}</p>
</form>
</body>
</html>
edit_book.html
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑出版社</title>
</head>
<body>
<h1>编辑出版社</h1>
<form action="/edit_publisher/" method="post">
    <input type="text" name="id" value="{{ edit_obj.id }}" style="display: none;">
    <input type="text" name="publisher_name" value="{{ edit_obj.name }}">
    <input type="submit" value="提交">
    <p style="color: red;">{{ error }}</p>
</form>
</body>
</html>
edit_publisher.html
技术分享图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>出版社列表</title>
</head>
<body>
{# a标签指向的位置找的也是urls.py文件中的对应关系的key。并不是直接找同级目录下的文件#}
<a href="/add_publisher/">添加新的出版社</a>
<table border="1">
    <thead>
    <tr>
        <th>序号</th>
        <th>ID</th>
        <th>出版社名称</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbady>
        {% for publisher in publisher_list %}
            <tr>
                <td>{{ forloop.counter }}</td>
                <td>{{ publisher.id }}</td>
                <td>{{ publisher.name }}</td>
                <td>
                    <a href="/delete_publisher/?id={{ publisher.id }}">删除</a>
                    <a href="/edit_publisher/?id={{ publisher.id }}">编辑</a>
                </td>
            </tr>
        {% endfor %}
    </tbady>
</table>
</body>
</html>
publisher_list.html

此时可以点运行,看看成果了,在8000后面加上下方数字后面的list即可操作书籍系统

技术分享图片

 

Django学习笔记2

原文:https://www.cnblogs.com/wlx97e6/p/9563135.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!