Django study notes 02 | 02 writing a Django application

First, install MySQL and install pymysql in Pycharm

Installation MySQLI can refer to this blog: MySQL 5.7.21 installation tutorial

Because Python2 the mysql library: mysqldb, and Python3 is: pymysql , so to the Pycharminstallation pymysql. Before installation and djangothe like, as shown below:

Second, the database configuration

Open mysite/settings.py, find DATABASES, modify the contents inside the red box:

Enter the code:

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

If you NAMEdo not write mysqlit, perform the following operation will complain:

Because Python3, remember to be at the same level __init__.py, add the following code files:

import pymysql
pymysql.install_as_MySQLdb()

Then Terminalenter the following command:

python manage.py migrate

This time they encountered a error:

According to the file location on the map display to find operations.py, modify decodeas encodeyou can, probably in the 146 line.

You may also encounter another mistake - operations.pya sibling named base.pyfile two lines 35, 36, commented:

Run the above command again, you will see:

Third, create a model

In this simple voting application, you need to create two models: issues Questionand options Choice. QuestionModel includes description of the problem and release date. ChoiceModel has two fields, options, and describes the current number of votes. Each option belonging to a problem.

Edit polls/models.pythe file:

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200) # 问题描述
    pub_date = models.DateTimeField('date published') # 发布时间


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200) # 选项描述
    votes = models.IntegerField(default=0) # 当前得票数

Fourth, the activation model

在文件 mysite/settings.pyINSTALLED_APPS 子项添加点式路径:

'polls.apps.PollsConfig',

结果如红框所示:

然后在 Terminal 中输入下面命令:

python manage.py makemigrations polls

将会看到类似于下面这样的输出:

下面进行迁移:

python manage.py sqlmigrate polls 0001

将会看到:

再次运行 migrate 命令,在数据库里创建新定义的模型的数据表:

python manage.py migrate

改变模型需要这三步:

  • 编辑 models.py 文件,改变模型。
  • 运行 python manage.py makemigrations 为模型的改变生成迁移文件。
  • 运行 python manage.py migrate 来应用数据库迁移。

五、初试 API

Terminal 输入下面命令,进入交互式 Python 命令行:

python manage.py shell

成功进入后,试试 database API 吧,试之前先修改一下 models.py 模型代码:

# Create your models here.

import datetime

from django.db import models
from django.utils import timezone


class Question(models.Model):
    question_text = models.CharField(max_length=200) # 问题描述
    pub_date = models.DateTimeField('date published') # 发布时间

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200) # 选项描述
    votes = models.IntegerField(default=0) # 当前得票数

    def __str__(self):
        return self.choice_text

然后就可以试试 database API 了:

from polls.models import Choice, Question
Question.objects.all()
from django.utils import timezone
q = Question(question_text="What's new?", pub_date=timezone.now())
q.save()
q.id
q.question_text
q.pub_date

需要退出交互式 Python 命令行时,按 Ctrl+Z 即可。

六、创建一个管理员账号

输入下面命令:

python manage.py createsuperuser

然后分别输入用户名、邮箱、密码、再次确认。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8TdCp824-1580284363358)(https://cdn.jsdelivr.net/gh/Wonz5130/My-Private-ImgHost/img/Snipaste_2020-01-28_16-59-06.png)]

七、启动开发服务

Django 的管理界面默认就是启用的。让我们启动开发服务器,看看它到底是什么样的。

如果开发服务器未启动,用以下命令启动它:

python manage.py runserver

打开浏览器,转到你本地域名的 “/admin/” 目录, – 比如 “http://127.0.0.1:8000/admin/” 。你应该会看见管理员登录界面:

输入刚才注册的用户名和密码,就能进入管理了:

八、向管理页面中加入投票应用

发现投票应用没在索引页面里显示,于是我们需要告诉管理页面,问题 Question 对象需要被管理。打开 polls/admin.py 文件,把它编辑成下面这样:

from django.contrib import admin

from .models import Question

admin.site.register(Question)

九、体验便捷的管理功能

现在我们向管理页面注册了问题 Question 类。Django 知道它应该被显示在索引页里,刷新一下页面就有了:

点击 “Questions” 。现在看到是问题 “Questions” 对象的列表 “change list” 。这个界面会显示所有数据库里的问题 Question 对象,你可以选择一个来修改。这里现在有我们在上一部分中创建的 “What’s up?” 问题。

点击 “What’s up?” 来编辑这个问题(Question)对象:

通过点击 “今天(Today)” 和 “现在(Now)” 按钮改变 “发布日期(Date Published)”。然后点击 “保存并继续编辑(Save and add another)”按钮。然后点击右上角的 “历史(History)”按钮。你会看到一个列出了所有通过 Django 管理页面对当前对象进行的改变的页面,其中列出了时间戳和进行修改操作的用户名:

十、致谢

编写你的第一个 Django 应用,第 2 部分

Pycharm数据库连接错误

django.db.utils.OperationalError: (1049, “Unknown database ‘djangodb’”)

发布了298 篇原创文章 · 获赞 391 · 访问量 25万+

Guess you like

Origin blog.csdn.net/Wonz5130/article/details/104107490