如何在Ubuntu 20.04上安装Django Web Framework

介绍 (Introduction)

Django is a full-featured Python web framework for developing dynamic websites and applications. Using Django, you can quickly create Python web applications and rely on the framework to do a good deal of the heavy lifting.

Django是用于开发动态网站和应用程序的全功能Python Web框架。 使用Django,您可以快速创建Python Web应用程序并依靠该框架来完成很多繁重的工作。

In this guide, you will get Django up and running on an Ubuntu 20.04 server. After installation, you will start a new project to use as the basis for your site.

在本指南中,您将启动Django并在Ubuntu 20.04服务器上运行。 安装后,您将启动一个新项目,以用作您的站点的基础。

不同的方法 (Different Methods)

There are different ways to install Django, depending upon your needs and how you want to configure your development environment. These have different advantages and one method may lend itself better to your specific situation than others.

有多种安装Django的方法,具体取决于您的需求以及如何配置开发环境。 这些具有不同的优势,一种方法可能比其他方法更适合您的特定情况。

Some of the different methods include:

一些不同的方法包括:

  • Global install from packages: The official Ubuntu repositories contain Django packages that can be installed with the conventional apt package manager. This is simple, but not as flexible as some other methods. Also, the version contained in the repositories may lag behind the official versions available from the project.

    从软件包进行全局安装 :官方的Ubuntu存储库包含Django软件包,可以使用常规apt软件包管理器进行安装。 这很简单,但没有其他方法灵活。 此外,存储库中包含的版本可能会落后于该项目提供的正式版本。

  • Install with pip in a virtual environment: You can create a self-contained environment for your projects using tools like venv and virtualenv. A virtual environment allows you to install Django in a project directory without affecting the larger system, along with other per-project customizations and packages. This is typically the most practical and recommended approach to working with Django.

    在虚拟环境中使用pip安装 :您可以使用venvvirtualenv类的工具为项目创建一个独立的环境。 虚拟环境允许您将Django与其他每个项目的自定义项和软件包一起安装在项目目录中,而不会影响较大的系统。 这通常是使用Django的最实用和推荐的方法。

  • Install the development version with git: If you wish to install the latest development version instead of the stable release, you can acquire the code from the Git repo. This is necessary to get the latest features/fixes and can be done within your virtual environment. Development versions do not have the same stability guarantees as more stable versions, however.

    使用git安装开发版本 :如果您希望安装最新的开发版本而不是稳定版本,则可以从Git存储库获取代码。 这是获取最新功能/修复程序所必需的,可以在您的虚拟环境中完成。 但是,开发版本的稳定性保证与更稳定的版本不同。

先决条件 (Prerequisites)

Before you begin, you should have a non-root user with sudo privileges available on your Ubuntu 20.04 server. To set this up, follow our Ubuntu 20.04 initial server setup guide.

在开始之前,您应该在Ubuntu 20.04服务器上拥有一个具有sudo特权的非root用户。 要进行设置,请遵循我们的Ubuntu 20.04初始服务器设置指南

从软件包进行全局安装 (Global Install from Packages)

If you wish to install Django using the Ubuntu repositories, the process is very straightforward.

如果您希望使用Ubuntu存储库安装Django,则过程非常简单。

First, update your local package index with apt:

首先,使用apt更新本地软件包索引:

  • sudo apt update

    sudo apt更新

Next, check which version of Python you have installed. 20.04 ships with Python 3.8 by default, which you can verify by typing:

接下来,检查已安装的Python版本。 默认情况下,Python 3.8附带20.04版,您可以通过输入以下内容进行验证:

  • python3 -V

    python3 -V

You should see output like this:

您应该看到如下输出:


   
   
Output
Python 3.8.2

Next, install Django:

接下来,安装Django:

  • sudo apt install python3-django

    sudo apt安装python3-django

You can test that the installation was successful by typing:

您可以通过键入以下命令来测试安装是否成功:

  • django-admin --version

    django-admin --version

   
   
Output
2.2.12

This means that the software was successfully installed. You may also notice that the Django version is not the latest stable version. To learn more about how to use the software, skip ahead to learn how to create sample project.

这表示该软件已成功安装。 您可能还会注意到Django版本不是最新的稳定版本。 要了解有关如何使用该软件的更多信息,请跳过以了解如何创建示例项目

在虚拟环境中使用pip安装 (Install with pip in a Virtual Environment)

The most flexible way to install Django on your system is within a virtual environment. We will show you how to install Django in a virtual environment that we will create with the venv module, part of the standard Python 3 library. This tool allows you to create virtual Python environments and install Python packages without affecting the rest of the system. You can therefore select Python packages on a per-project basis, regardless of conflicts with other projects’ requirements.

在系统上安装Django的最灵活的方法是在虚拟环境中。 我们将向您展示如何在venv模块(标准Python 3库的一部分)创建的虚拟环境中安装Django。 使用此工具,您可以创建虚拟Python环境并安装Python软件包,而不会影响系统的其余部分。 因此,您可以根据每个项目选择Python软件包,而与其他项目的要求不冲突。

Let’s begin by refreshing the local package index:

让我们从刷新本地包索引开始:

  • sudo apt update

    sudo apt更新

Check the version of Python you have installed:

检查您安装的Python版本:

  • python3 -V

    python3 -V

   
   
Output
Python 3.8.2

Next, let’s install pip and venv from the Ubuntu repositories:

接下来,让我们从Ubuntu存储库安装pipvenv

  • sudo apt install python3-pip python3-venv

    须藤apt install python3-pip python3-venv

Now, whenever you start a new project, you can create a virtual environment for it. Start by creating and moving into a new project directory:

现在,无论何时启动新项目,都可以为其创建虚拟环境。 首先创建并移至新的项目目录:

  • mkdir ~/newproject

    mkdir〜 /新项目

  • cd ~/newproject

    cd〜 /新项目

Next, create a virtual environment within the project directory using the python command that’s compatible with your version of Python. We will call our virtual environment my_env, but you should name it something descriptive:

接下来,使用与您的Python版本兼容的python命令在项目目录中创建一个虚拟环境。 我们将虚拟环境my_env ,但您应使用描述性名称:

  • python3 -m venv my_env

    python3 -m venv my_env

This will install standalone versions of Python and pip into an isolated directory structure within your project directory. A directory will be created with the name you select, which will hold the file hierarchy where your packages will be installed.

这会将Python的独立版本和pip安装到项目目录中的隔离目录结构中。 将使用您选择的名称创建一个目录,该目录将保存将要安装软件包的文件层次结构。

To install packages into the isolated environment, you must activate it by typing:

要将软件包安装到隔离的环境中,必须通过输入以下内容将其激活:

  • source my_env/bin/activate

    源my_env / bin / activate

Your prompt should change to reflect that you are now in your virtual environment. It will look something like (my_env)username@hostname:~/newproject$.

您的提示应更改以反映您现在处于虚拟环境中。 看起来像( my_env )username@hostname:~/newproject$

In your new environment, you can use pip to install Django. Regardless of your Python version, pip should just be called pip when you are in your virtual environment. Also note that you do not need to use sudo since you are installing locally:

在新环境中,您可以使用pip安装Django。 无论您使用的是pip Python版本,在虚拟环境中都应将pip称为pip 。 另请注意,由于您是在本地安装的, 因此无需使用sudo

  • pip install django

    pip安装Django

You can verify the installation by typing:

您可以通过键入以下内容来验证安装:

  • django-admin --version

    django-admin --version

   
   
Output
3.0.8

Note that your version may differ from the version shown here.

请注意,您的版本可能与此处显示的版本不同。

To leave your virtual environment, you need to issue the deactivate command from anywhere on the system:

要退出虚拟环境,需要从系统上的任何位置发出deactivate命令:

  • deactivate

    停用

Your prompt should revert to the conventional display. When you wish to work on your project again, re-activate your virtual environment by moving back into your project directory and activating:

您的提示应恢复为常规显示。 当您希望再次处理项目时,请移回项目目录并激活:

  • cd ~/newproject

    cd〜 /新项目

  • source my_env/bin/activate

    源my_env / bin / activate

使用Git安装的开发版本 (Development Version Install with Git)

If you need a development version of Django, you can download and install Django from its Git repository. Let’s do this from within a virtual environment.

如果您需要Django的开发版本,则可以从Django的Git存储库下载并安装Django。 让我们在虚拟环境中执行此操作。

First, let’s update the local package index:

首先,让我们更新本地包索引:

  • sudo apt update

    sudo apt更新

Check the version of Python you have installed:

检查您安装的Python版本:

  • python3 -V

    python3 -V

   
   
Output
Python 3.8.2

Next, install pip and venv from the official repositories:

接下来,从官方存储库安装pipvenv

  • sudo apt install python3-pip python3-venv

    sudo apt安装python3-pip python3-venv

The next step is cloning the Django repository. Between releases, this repository will have more up-to-date features and bug fixes at the possible expense of stability. You can clone the repository to a directory called ~/django-dev within your home directory by typing:

下一步是克隆Django存储库。 在发行版之间,此存储库将具有更多最新功能和错误修复,而可能会牺牲稳定性。 您可以通过输入以下命令将存储库克隆到主目录中的~/ django-dev目录中:

  • git clone git://github.com/django/django ~/django-dev

    git clone git://github.com/django/django〜/ django-dev

Change to this directory:

转到此目录:

  • cd ~/django-dev

    cd〜/ django-dev

Create a virtual environment using the python command that’s compatible with your installed version of Python:

使用与您安装的Python版本兼容的python命令创建虚拟环境:

  • python3 -m venv my_env

    python3 -m venv my_env

Activate it:

激活它:

  • source my_env/bin/activate

    源my_env / bin / activate

Next, you can install the repository using pip. The -e option will install in “editable” mode, which is necessary when installing from version control:

接下来,您可以使用pip安装存储库。 -e选项将以“可编辑”模式安装,这是从版本控制安装时必需的:

  • pip install -e ~/django-dev

    pip install -e〜/ django-dev

You can verify that the installation was successful by typing:

您可以通过键入以下命令来验证安装是否成功:

  • django-admin --version

    django-admin --version

   
   
Output
3.2

Again, the version you see displayed may not match what is shown here.

同样,您看到的版本可能与此处显示的版本不匹配。

You now have the latest version of Django in your virtual environment.

现在,您在虚拟环境中拥有最新版本的Django。

创建一个示例项目 (Creating a Sample Project)

With Django installed, you can begin building your project. We will go over how to create a project and test it on your development server using a virtual environment.

安装Django之后,您就可以开始构建项目了。 我们将介绍如何使用虚拟环境创建项目并在开发服务器上对其进行测试。

First, create a directory for your project and change into it:

首先,为您的项目创建一个目录并更改为该目录:

  • mkdir ~/django-test

    mkdir〜/ django-test

  • cd ~/django-test

    cd〜/ django-test

Next, create your virtual environment:

接下来,创建您的虚拟环境:

  • python3 -m venv my_env

    python3 -m venv my_env

Activate the environment:

激活环境:

  • source my_env/bin/activate

    源my_env / bin / activate

Install Django:

安装Django:

  • pip install django

    pip安装Django

To build your project, you can use django-admin with the startproject command. We will call our project djangoproject, but you can replace this with a different name. startproject will create a directory within your current working directory that includes:

要构建项目,可以将django-adminstartproject命令一起使用。 我们将我们的项目djangoproject ,但是您可以将其替换为其他名称。 startproject将在当前工作目录中创建一个目录,其中包括:

  • A management script, manage.py, which you can use to administer various Django-specific tasks.

    管理脚本manage.py ,可用于管理各种特定于Django的任务。

  • A directory (with the same name as the project) that includes the actual project code.

    包含实际项目代码的目录(与项目名称相同)。

To avoid having too many nested directories, however, let’s tell Django to place the management script and inner directory in the current directory (notice the ending dot):

但是,为了避免嵌套目录过多,让我们告诉Django将管理脚本和内部目录放在当前目录中(注意结尾的点):

  • django-admin startproject djangoproject .

    django-admin startproject djangoproject 。

To migrate the database (this example uses SQLite by default), let’s use the migrate command with manage.py. Migrations apply any changes you’ve made to your Django models to your database schema.

要迁移数据库(此示例默认情况下使用SQLite),让我们将migrate命令与manage.py迁移会将您对Django 模型所做的所有更改都应用到数据库架构中。

To migrate the database, type:

要迁移数据库,请键入:

  • python manage.py migrate

    python manage.py迁移

You will see output like the following:

您将看到如下输出:


   
   
Output
Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying sessions.0001_initial... OK

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

  • python manage.py createsuperuser

    python manage.py createsuperuser

You will be prompted for a username, an email address, and a password for your user.

系统将提示您输入用户名,电子邮件地址和用户密码。

在Django设置中修改ALLOWED_HOSTS (Modifying ALLOWED_HOSTS in the Django Settings)

To successfully test your application, you will need to modify one of the directives in the Django settings.

要成功测试您的应用程序,您将需要修改Django设置中的指令之一。

Open the settings file by typing:

通过键入以下内容来打开设置文件:

  • nano ~/django-test/djangoproject/settings.py

    纳米〜/ django-test / djangoproject /settings.py

Inside, locate the ALLOWED_HOSTS directive. This defines a list of addresses or domain names that may be used to connect to the Django instance. An incoming request with a Host header that is not in this list will raise an exception. Django requires that you set this to prevent a certain class of security vulnerability.

在内部,找到ALLOWED_HOSTS指令。 这定义了可用于连接到Django实例的地址或域名列表。 主机头不在此列表中的传入请求将引发异常。 Django要求您对此进行设置,以防止出现某类安全漏洞。

In the square brackets, list the IP addresses or domain names that are associated with your Django server. Each item should be listed in quotations, with separate entries separated by a comma. If you want requests for an entire domain and any subdomains, prepend a period to the beginning of the entry:

在方括号中,列出与Django服务器关联的IP地址或域名。 每个项目都应以引号列出,并用逗号分隔各个单独的条目。 如果要请求整个域和任何子域,请在条目的开头加上句点:

~/django-test/djangoproject/settings.py
〜/ django-test / djangoproject / settings.py
ALLOWED_HOSTS = ['your_server_ip_or_domain', 'your_second_ip_or_domain', . . .]

When you are finished, save the file and exit your editor.

完成后,保存文件并退出编辑器。

测试开发服务器 (Testing the Development Server)

Once you have a user, you can start up the Django development server to see what a fresh Django project looks like. You should only use this for development purposes. When you are ready to deploy, be sure to follow Django’s guidelines on deployment carefully.

拥有用户后,您可以启动Django开发服务器以查看新的Django项目的外观。 您仅应将此用于开发目的。 准备部署时,请务必仔细遵循Django的部署指南

Before you try the development server, make sure you open the appropriate port in your firewall. If you followed the initial server setup guide and are using UFW, you can open port 8000 by typing:

在尝试开发服务器之前,请确保在防火墙中打开适当的端口。 如果您遵循初始服务器设置指南并使用UFW,则可以通过键入以下内容打开端口8000

  • sudo ufw allow 8000

    sudo ufw允许8000

Start the development server:

启动开发服务器:

  • python manage.py runserver your_server_ip:8000

    python manage.py runserver your_server_ip :8000

Visit your server’s IP address followed by :8000 in your web browser:

在网络浏览器中访问服务器的IP地址,然后输入:8000

http://your_server_ip:8000

You should see something that looks like this:

您应该看到如下所示的内容:

To access the admin interface, add /admin/ to the end of your URL:

要访问管理界面,请在网址末尾添加/admin/

http://your_server_ip:8000/admin/

This will take you to a log in screen:

这将带您进入登录屏幕:

If you enter the admin username and password that you just created, you will have access to the main admin section of the site:

如果输入刚刚创建的管理员用户名和密码,则可以访问该站点的主要管理员部分:

For more information about working with the Django admin interface, please see “How To Enable and Connect the Django Admin Interface.”

有关使用Django管理界面的更多信息,请参阅“如何启用和连接Django管理界面”。

When you are finished looking through the default site, you can stop the development server by typing CTRL-C in your terminal.

当您浏览完默认站点后,可以在终端中键入CTRL-C来停止开发服务器。

The Django project you’ve created provides the structural basis for designing a more complete site. Check out the Django documentation for more information about how to build your applications and customize your site.

您创建的Django项目为设计更完整的站点提供了结构基础。 请查阅Django文档,以获取有关如何构建应用程序和自定义网站的更多信息。

结论 (Conclusion)

You should now have Django installed on your Ubuntu 20.04 server, providing the main tools you need to create powerful web applications. You should also know how to start a new project and launch the developer server. Leveraging a complete web framework like Django can help make development faster, allowing you to concentrate only on the unique aspects of your applications.

现在,您应该已经在Ubuntu 20.04服务器上安装了Django,并提供了创建强大的Web应用程序所需的主要工具。 您还应该知道如何启动新项目并启动开发人员服务器。 利用像Django这样的完整Web框架可以帮助加快开发速度,使您仅专注于应用程序的独特方面。

If you would like more information about working with Django, including in-depth discussions of things like models and views, please see our Django development series.

如果您想了解有关使用Django的更多信息,包括对模型视图之类的深入讨论,请参阅我们的Django开发系列

翻译自: https://www.digitalocean.com/community/tutorials/how-to-install-the-django-web-framework-on-ubuntu-20-04

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值