Python学习笔记——Day10

Python学习笔记——Day10

继续昨天的内容。

注册应用

昨天已经注册了一个应用,今天我们就通过这个应用做一些事。先写一个简单页面,比如"hello world"。

修改应用目录下面的views.py

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

# Create your views here.

def index(request):
    return HttpResponse("<h3>hello world!<h3>")

再在应用目录新建一个urls.py用以映射URL:

from django.urls import path

from a_test import views

urlpatterns  [
	path('', views.index, name='index')
]

修改项目下的urls.py文件,合并我们刚刚在应用中配置的URL:

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

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

我们通过include()发方法将应用中的url配置文件合并到项目的url配置文件中,并映射到’a_test/'路径下,完成这些就大功告成,接下来我们只需要运行项目:

python manage.py runserver

浏览器地址栏中输入http://localhost:8000/a_test/就可以访问到我们刚刚写的“hello world”。

视图

我们还可以通过视图模板来显示网页,在项目目录创建一个templates文件夹,在settings.py中配置模板路径:

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',
            ],
        },
    },
]

创建模板页面:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>

<body>
    <h1>{{ message }}</h1>
</body>

</html>

{{ message }}是模板占位符语法,属于Django模板语言的一部分。继续修改应用目录下的views.py:

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

# Create your views here.

def index(request):
    return render(request, 'index.html', {'message': 'hello world!!!'})

重新运行我们的项目:

python manage.py runserver

刷新后,hello world!!!出现了。

设计模型

设计两张表用以存储数据,一张人物表,一张图书表。

  • 图书表结构设计:
    • 表名:book
    • 书名:name
    • 发布时间:pub_time
  • 人物表结构设计:
    • 表名:author
    • 作者名:author
    • 作者性别:gender
    • 作品:book
      结构关系为图书人物一对多

在settings.py中,我们可以通过DATABASES进行配置数据库,Django默认使用SQLite数据库

接下来我们在a_test应用中models.py文件中定义模型类

from django.db import models

# Create your models here.
class Book(models.Model):
    name = models.CharField(max_length=32)
    pub_time = models.DateTimeField()

    def __str_(self):
        return "%d" % self.pk

class People(models.Model):
    name = models.CharField(max_length=32)
    gender = models.BooleanField()
    book = models.ForeignKey('Book',on_delete=models.CASCADE)

    def __str_(self):
        return "%d" % self.pk

在views.py中创建一个接口用以调用方法存储数据:

def makeData(request):
    book = Book()
    book.name = "射雕英雄传"
    book.pub_date=datetime(year=1990,month=1,day=10)
    book.save()
    # 人物
    people = People()
    people.name = "郭靖"
    people.gender = True
    people.book = book
    people.save()
    people = People()
    people.name = "黄蓉"
    people.gender = False
    people.book = book
    people.save()
    # 返回
    result = [book, people]
    return HttpResponse("success")

在urls.py中添加一个url配置:

from django.urls import path

from a_test import views

urlpatterns = [
    path('', views.index, name='index'),
    path('make/', views.makeData, name='make'),
]

通过浏览器访问http://localhost:8000/a_test/make就将数据保存到数据库中了,接下来我们修改views.py中的index方法:

def index(request):
    people = People.objects.all()
    return render(request, 'index.html', {'people': people})

修改templates模板中index.html文件:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>

<body>
    <h1>人物列表</h1>
    <ul>
        {%for p in people%}
        <li>
            {{ p.name }},
            性别:
            {%if p.gender == True%}
            男
            {% else %}
            女
            {% endif %},
            所属图书:{{ p.book.name }},
            图书发布时间:{{ p.book.pub_time }}
        </li>
        {%endfor%}
    </ul>
</body>

</html>

最后访问http://localhost:8000/a_test/可以看到数据显示在页面中。这样我们的简单入门就完成了。

结语

这只是一个非常简单的入门,虽说只是一个简单的演示,但可以对Django框架有一个大体的认识,明天周六,继续学习!
如果你发现我的文章哪里有错误或者有什么好的想法可以联系我,我们一起学习共同进步,我的邮箱地址是[email protected]

let’s do more of those!

发布了26 篇原创文章 · 获赞 2 · 访问量 2335

猜你喜欢

转载自blog.csdn.net/qq_42909545/article/details/103318236