django连接数据库
A free and open-source web framework written in Python, Django allows for scalability, re-usability, and rapid development.
Django是一个用Python编写的免费开放源代码Web框架,可实现可伸缩性,可重用性和快速开发。
In this tutorial, you will learn how to set up the initial foundation for a blog website with connections to a MySQL database. This will involve creating the skeleton structure of the blog web application using django-admin
, creating the MySQL database and then connecting the web application to the database.
在本教程中,您将学习如何为连接到MySQL数据库的博客网站建立初始基础。 这将涉及使用django-admin
创建博客Web应用程序的框架结构,创建MySQL数据库,然后将Web应用程序连接到数据库。
Note that this will provide you with a development environment in which to work on your blog web app, but you will need to take more steps before you put your blog live on the internet, and will need to set up domain names, and add additional layers of security.
请注意,这将为您提供一个可以在博客Web应用程序上工作的开发环境,但是在将博客发布到Internet上之前,您需要采取更多步骤,并且需要设置域名,并添加其他内容。安全层。
You should have a Python environment set up on your server. In this tutorial, we’ll be using an Ubuntu 20.04 server, but as the focus of this tutorial is on Django, the principles should be applicable for other operating systems.
您应该在服务器上设置一个Python环境。 在本教程中,我们将使用Ubuntu 20.04服务器,但是由于本教程的重点是Django,因此该原理应适用于其他操作系统。
To set up Python, follow our tutorial How To Install Python 3 and Set Up a Programming Environment on an Ubuntu 20.04 Server.
要设置Python,请遵循我们的教程如何在Ubuntu 20.04服务器上安装Python 3和设置编程环境 。
With Python in place, we can move on to creating our app.
有了Python,我们就可以继续创建应用了。
We’ll be using MySQL as our database. You may alternately wish to use another database or already have a database installed, in which case you should skip this step.
我们将使用MySQL作为数据库。 您可能希望使用另一个数据库或已经安装了数据库,在这种情况下,您应该跳过此步骤。
To install MySQL to an Ubuntu 20.04 server, type the following:
要将MySQL安装到Ubuntu 20.04服务器,请键入以下命令:
You should receive the following output:
您应该收到以下输出:
Output
● mysql.service - MySQL Community Server
Loaded: loaded (/lib/systemd/system/mysql.service; enabled; vendor preset: enabled)
Active: active (running) since Thu 2020-05-07 20:22:51 UTC; 3min 7s ago
Main PID: 2052 (mysqld)
Status: "Server is operational"
Tasks: 38 (limit: 1137)
Memory: 317.4M
CGroup: /system.slice/mysql.service
└─2052 /usr/sbin/mysqld
Ensure that the feedback you receive states that your MySQL server is active
. Once that is true, you can continue this tutorial.
确保收到的反馈表明MySQL服务器active
。 一旦这是对的,您就可以继续本教程。
In order to lay the groundwork for our application, we need to generate the project skeleton using the django-admin
command. This generated project will be the foundation of our blog app.
为了为我们的应用程序打下基础,我们需要使用django-admin
命令生成项目框架。 这个生成的项目将成为我们博客应用程序的基础。
Navigate to the directory where you would like to build your blog app. Within that directory, we’ll create a specific directory to build the app. Call the directory something meaningful for the app you are building. As an example, we’ll call ours my_blog_app
.
导航到您要构建博客应用程序的目录。 在该目录中,我们将创建一个特定目录来构建应用程序。 将目录命名为对您正在构建的应用有意义的目录。 作为示例,我们将其称为my_blog_app
。
mkdir my_blog_app
mkdir my_blog_app
Now, navigate to the newly created directory:
现在,导航到新创建的目录:
cd my_blog_app
cd my_blog_app
Next, move into the programming environment you would like to use for working in Django. You can use an existing one, or create a new one. We’ll call ours env
, but you should use a name that is meaningful to you. Once it’s created you can activate it.
接下来,进入要在Django中使用的编程环境。 您可以使用现有的,也可以创建一个新的。 我们将其称为env
,但是您应该使用一个对您有意义的名称。 创建完成后,即可激活它。
python3 -m venv env
python3 -m venv env
. env/bin/activate
。 env / bin /激活
Now install Django into this environment if you have not done so already:
如果尚未将Django安装到此环境中,请执行以下操作:
While in the my_blog_app
directory, we will generate a project by running the following command:
在my_blog_app
目录中,我们将通过运行以下命令来生成项目:
django-admin startproject blog
django-admin startproject 博客
Verify that it worked by navigating to the blog/
directory:
通过导航到blog/
目录来验证它是否有效:
The blog/
directory should have been created in the current directory, ~/my_blog_app/
, after running the previous django-admin
command.
运行先前的django-admin
命令后,应该在当前目录~/my_blog_app/
创建blog/
目录。
Run ls
to verify that the necessary items were created. There should be a blog
directory and a manage.py
file:
运行ls
验证是否已创建必要的项目。 应该有一个blog
目录和一个manage.py
文件:
Output
blog manage.py
Now that you’ve created a project directory containing the initial start of your blog application, we can continue on to the next step.
现在,您已经创建了一个包含博客应用程序初始启动位置的项目目录,接下来我们可以继续下一步。
Since we’ve generated the skeleton project, we now have a settings.py
file.
由于我们已经生成了骨架项目,因此现在有了settings.py
文件。
In order for our blog to have the correct time associated with our area, we will edit the settings.py
file so that it will be using your current time zone. You can use this list of time zones as a reference. For our example, we will be using America/New_York
time.
为了使我们的博客具有与我们所在地区相关的正确时间,我们将编辑settings.py
文件,使其使用您当前的时区。 您可以使用此时区列表作为参考。 对于我们的示例,我们将使用America/New_York
时间。
We want to edit the file, so let’s open the path to the file with our text editor of choice. Here, we’ll use nano.
我们要编辑文件,所以让我们使用选择的文本编辑器打开文件的路径。 在这里,我们将使用nano。
Since we are editing the TIME_ZONE
field, we’ll navigate to the bottom section of the file, similar to below.
由于我们正在编辑TIME_ZONE
字段,因此我们将导航至文件的底部,类似于以下内容。
...
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
...
We are going to modify the TIME_ZONE
line so that it is set to your current time zone. We will be using the time zone for New York in this example:
我们将修改TIME_ZONE
行,以便将其设置为您当前的时区。 在此示例中,我们将使用纽约的时区:
...
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = True
...
Let’s keep the file open because we need to add a path for our static files. The files that get served from your Django web application are referred to as static files. This could include any necessary files to render the complete web page, including JavaScript, CSS, and images.
让我们保持文件打开状态,因为我们需要为静态文件添加路径。 从Django Web应用程序提供的文件称为静态文件 。 这可能包括呈现整个网页所需的任何文件,包括JavaScript,CSS和图像。
Go to the end of the settings.py
file and add STATIC_ROOT
as shown below:
转到settings.py
文件的末尾并添加STATIC_ROOT
,如下所示:
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
Now that we’ve added the time zone and the path for static files, we should next add our IP to the list of allowed hosts. Navigate to the line of the settings.py
file where it says ALLOWED_HOSTS
, it’ll be towards the top of the settings.py
file.
现在我们已经添加了时区和静态文件的路径,接下来我们应该将IP添加到允许的主机列表中。 导航到settings.py
文件的显示ALLOWED_HOSTS
,它将位于settings.py
文件的顶部。
...
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['your server IP address']
# Application definition
...
Add your server’s IP address between the square brackets and single quotes.
在方括号和单引号之间添加服务器的IP地址。
Once you are satisfied with the changes you have made, save the file. If you are in nano, you can do so by pressing CTRL
+ X
and then y
to confirm changes.
对所做的更改满意后,请保存文件。 如果您使用的是nano,则可以通过按CTRL
+ X
,然后按y
确认更改来进行操作。
You’ve successfully edited your settings.py
file so that the proper time zone has been configured. You’ve also added the path for your static files, and set your ip address
to be an ALLOWED_HOST
for your application.
您已经成功编辑了settings.py
文件,从而配置了正确的时区。 您还添加了静态文件的路径,并将ip address
设置为应用程序的ALLOWED_HOST
。
Finally, let’s create an administrative user so that you can use the Djano admin interface. Let’s do this with the createsuperuser
command:
最后,让我们创建一个管理用户,以便您可以使用Djano admin界面 。 让我们使用createsuperuser
命令执行此createsuperuser
:
You will be prompted for a username, an email address, and a password for your user.
系统将提示您输入用户名,电子邮件地址和用户密码。
At this point we can go on to setting up our database connection.
此时,我们可以继续建立数据库连接。
In order to use MySQL with our project, we will need a Python 3 database connector library compatible with Django. So, we will install the database connector, mysqlclient
, which is a forked version of MySQLdb
.
为了在我们的项目中使用MySQL,我们需要一个与Django兼容的Python 3数据库连接器库。 因此,我们将安装数据库连接器mysqlclient
,它是MySQLdb
的分支版本。
First ensure that you have python3-dev
installed. You can install python3-dev
by running the following command:
首先确保您已安装python3-dev
。 您可以通过运行以下命令来安装python3-dev
:
We can now install the necessary Python and MySQL development headers and libraries:
现在,我们可以安装必要的Python和MySQL开发标头和库:
Press y
and ENTER
to accept the installation.
按y
和ENTER
接受安装。
Once the installation is complete, we will use pip3
to install the mysqlclient
library from PyPi
. Since our version of pip
points to pip3
, we can just use pip
.
安装完成后,我们将使用pip3
从PyPi
安装mysqlclient
库。 由于我们的pip
版本指向pip3
,因此我们只能使用pip
。
You will receive output similar to this, verifying that it is installing properly:
您将收到与此类似的输出,验证其安装正确:
successfully installed mysqlclient
...
Successfully installed mysqlclient-1.4.6
We have now successfully installed the MySQL client using the PyPi mysqlclient
connector library.
现在,我们已经使用PyPi mysqlclient
连接器库成功安装了MySQL客户端。
Now that the skeleton of your Django application has been set up and mysqlclient
and mysql-server
have been installed, we will to need to configure your Django backend for MySQL compatibility.
现在,已经设置了Django应用程序的框架,并安装了mysqlclient
和mysql-server
,我们将需要配置Django后端以实现MySQL兼容性。
Log in via the MySQL root with the following command:
使用以下命令通过MySQL根目录登录:
We’ll know we are in the MySQL server when our prompt changes:
当提示更改时,我们将知道我们在MySQL服务器中:
Let’s inspect the current databases with the following command:
让我们使用以下命令检查当前数据库:
You’ll see output similar to the following, assuming that you haven’t created any databases yet:
假设尚未创建任何数据库,您将看到类似于以下的输出:
Output
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
+--------------------+
4 rows in set (0.00 sec)
Note: If you get an error while trying to connect, verify that your password is correct and that you’ve properly installed MySQL. Otherwise revisit the tutorial on how to install and configure MySQL.
注意:如果尝试连接时遇到错误,请确认密码正确并且已正确安装MySQL。 否则,请重新访问有关如何安装和配置MySQL的教程 。
By default, you will have 4 databases already created, information_schema
, MySQL
, performance_schema
and sys
. We won’t need to touch these, as they contain information important for the MySQL server itself.
默认情况下,您将已经创建了4个数据库information_schema
, MySQL
, performance_schema
和sys
。 我们不需要碰这些,因为它们包含对MySQL服务器本身很重要的信息。
Now, that you’ve successfully logged into your MySQL server, we will create the initial database that will hold the data for our blog.
现在,您已经成功登录到MySQL服务器,我们将创建一个初始数据库,该数据库将保存我们博客的数据。
To create a database in MySQL run the following command, using a meaningful name for your database:
要在MySQL中创建数据库,请使用数据库的有意义名称运行以下命令:
CREATE DATABASE blog_data;
创建数据库blog_data ;
Upon successful creation of the database, you will see the following output:
成功创建数据库后,您将看到以下输出:
Output
Query OK, 1 row affected (0.00 sec)
Note: If you see the following output:
注意:如果看到以下输出:
database creation failed
ERROR 1007 (HY000): Can't create database blog_data; database exists
Then, as the error states, a database of the name blog_data
already exists.
然后,作为错误状态,已经存在名称为blog_data
的数据库。
And if you see the following MySQL error, it means there’s a MySQL syntax error. Verify that you’ve entered the command exactly as shown in this tutorial.
并且,如果您看到以下MySQL错误,则表明存在MySQL语法错误。 验证您输入的命令与本教程中显示的完全相同。
database creation failed
ERROR 1064 (42000): You have an error in your SQL syntax;
Next, verify that the database is now listed in your list of available databases:
接下来,验证数据库现在已列在可用数据库列表中:
You should see that the blog_data
database is among the databases included in the output:
您应该看到blog_data
数据库位于输出中包括的数据库中:
output
+--------------------+
| Database |
+--------------------+
| information_schema |
| blog_data |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
Next, we are going to create a separate MySQL user account that we will use exclusively to operate our new database. Creating specific databases and accounts can support us from a management and security standpoint. We will use the name djangouser in this guide, but feel free to use whatever name is relevant for you.
接下来,我们将创建一个单独MySQL用户帐户,该帐户将专门用于操作新数据库。 从管理和安全的角度来看,创建特定的数据库和帐户可以为我们提供支持。 在本指南中,我们将使用名称djangouser ,但请随意使用与您相关的任何名称。
We are going to create this account, set a password, and grant access to the database we created. We can do this by typing the following command. Remember to choose a strong password here for your database user where we have password
:
我们将创建该帐户,设置密码,并授予对我们创建的数据库的访问权限。 我们可以通过键入以下命令来做到这一点。 记住在这里为您的数据库用户选择一个强密码,我们有password
:
CREATE USER 'djangouser'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
创建用户' djangouser '@'%'用mysql_native_password标识' 密码 ';
Next, let the database know that our djangouser should have complete access to the database we set up:
接下来,让数据库知道我们的djangouser应该具有对我们设置的数据库的完全访问权限:
GRANT ALL ON blog_data.* TO 'djangouser'@'%';
全部授予blog_data 。* TO'djangouser '@'%';
You now have a database and user account, each made specifically for Django. We need to flush the privileges so that the current instance of MySQL knows about the recent changes we’ve made:
现在,您有一个数据库和用户帐户,每个数据库帐户和用户帐户都是专门为Django创建的。 我们需要清除特权,以便MySQL的当前实例知道我们最近所做的更改:
With that complete, you can exit MySQL server by typing EXIT;
or pressing CTRL
+ D
.
完成后,您可以通过键入EXIT;
退出MySQL服务器EXIT;
或按CTRL
+ D
Finally, we will be adding the database connection credentials to your Django application.
最后,我们将数据库连接凭据添加到您的Django应用程序中。
Note: It is important to remember that connection settings, according to the Django documentation, are used in the following order: - OPTIONS
- NAME
, USER
, PASSWORD
, HOST
, PORT
- MySQL option files.
注意:重要的是要记住,根据Django文档,连接设置按以下顺序使用:- OPTIONS
- NAME
, USER
, PASSWORD
, HOST
, PORT
MySQL option files.
Let’s make the changes needed to connect your Django blog app to MySQL.
让我们进行必要的更改,以将Django博客应用程序连接到MySQL。
Navigate to the settings.py
file and replace the current DATABASES
lines with the following. We will configure your database dictionary so that it knows to use MySQL as your database backend and from what file to read your database connection credentials.
导航到settings.py
文件,并用以下内容替换当前的DATABASES
行。 我们将配置您的数据库字典,以便它知道使用MySQL作为数据库后端以及从哪个文件读取数据库连接凭据。
Delete the lines that are there and replace it with the following, being sure to keep the right number of curly braces.
删除其中的行,并替换为以下内容,并确保保留正确数量的花括号。
...
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'read_default_file': '/etc/mysql/my.cnf',
},
}
}
...
Save and close the file.
保存并关闭文件。
Next, let’s edit the config file so that it has your MySQL credentials. Use nano as sudo
to edit the file and add the following information:
接下来,让我们编辑配置文件,使其具有您MySQL凭据。 使用nano作为sudo
编辑文件并添加以下信息:
Add the following lines and include your relevant information.
添加以下行,并包含您的相关信息。
...
[client]
database = blog_data
user = djangouser
password = your_actual_password
default-character-set = utf8
You’ll notice that utf8
is set as the default encoding, this is a common way to encode unicode data in MySQL. When you are sure that your details are correct, save and close the file.
您会注意到utf8
设置为默认编码,这是在MySQL中对unicode数据进行编码的一种常用方法。 当确定您的详细信息正确无误时,请保存并关闭文件。
Once the file has been edited, we need to restart MySQL for the changes to take effect.
编辑完文件后,我们需要重新启动MySQL才能使更改生效。
Please note that restarting MySQL takes a few seconds, so please be patient.
请注意,重启MySQL需要花费几秒钟,因此请耐心等待。
We need to verify that the configurations in Django detect your MySQL server properly. We can do this by running the server. If it fails, it means that the connection isn’t working properly. Otherwise, the connection is valid.
我们需要验证Django中的配置可以正确检测到您MySQL服务器。 我们可以通过运行服务器来做到这一点。 如果失败,则表示连接无法正常工作。 否则,连接有效。
Let’s first apply our changes to django with the following:
首先,使用以下命令将更改应用于django:
We’ll need to navigate to the following directory:
我们需要导航到以下目录:
From there, we can run the following command:
从那里,我们可以运行以下命令:
python manage.py runserver your-server-ip:8000
python manage.py runserver your-server-ip :8000
You will now see output similar to the following:
现在,您将看到类似于以下内容的输出:
Output
Performing system checks...
System check identified no issues (0 silenced).
You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
January 4, 2018 - 15:45:39
Django version 2.0.1, using settings 'blog.settings'
Starting development server at http://your-server-ip:8000/
Quit the server with CONTROL-C.
Note: You will see that you have unapplied migrations in the output. But, don’t worry, this will be addressed in the upcoming tutorials. This does not affect the initial setup of our application. Please continue.
注意:您将看到输出中有未应用的迁移。 但是,请放心,这将在以后的教程中解决。 这不会影响我们的应用程序的初始设置。 请继续。
Follow the instructions from the output and follow the suggested link, http://your-server-ip:8000/
, to view your web application and to verify that it is working properly.
请遵循输出中的指示信息,并使用建议的链接http:// your-server-ip :8000/
来查看您的Web应用程序并验证其是否正常运行。
If your page appears similar to the screenshot above, your Django application is working as expected!
如果您的页面看起来与上面的屏幕截图类似,则说明您的Django应用程序正在按预期运行!
When you are done with testing your app, you can press CTRL
+ C
to stop the runserver
command. This will return you to the your programming environment.
测试完应用程序后,可以按CTRL
+ C
停止runserver
命令。 这将使您返回到编程环境。
When you are ready to leave your Python environment, you can run the deactivate
command:
当您准备离开Python环境时,可以运行deactivate
命令:
Deactivating your programming environment will put you back to the terminal command prompt.
停用编程环境将使您返回到终端命令提示符。
In this tutorial, you created the initial foundation of your Django blog. You have installed, configured and connected MySQL to the Django backend. You’ve also added some important information to your application’s settings.py
file such as TIME_ZONE
and ALLOWED_HOSTS
.
在本教程中,您创建了Django博客的初始基础。 您已经安装,配置了MySQL并将其连接到Django后端。 您还向应用程序的settings.py
文件中添加了一些重要信息,例如TIME_ZONE
和ALLOWED_HOSTS
。
Now that these basic settings and configurations are complete, you can now begin to develop models and apply migrations in your Django application.
现在,这些基本设置和配置已经完成,您现在可以开始开发模型并在Django应用程序中应用迁移。
django连接数据库