如何在 Python 中使用 Django 构建自己的网站
介绍
Django是一个免费和开源的Python网络框架。
为什么要使用Django?
它非常快。
带有许多预先存在的功能,如用户身份验证、站点映射、RSS提要。
它非常安全,可以防止许多安全错误,如SQL注入、跨站点脚本、点击劫持等。
它具有很强的可扩展性,因此即使在网络流量非常高的情况下也可以使用。
现在您知道我们为什么要使用Django来构建我们的Web应用程序。让我们开始为它做基础工作。
设置环境
在构建我们的Web应用程序时,我们将使用在我们的网站工作区之外不需要的各种包。为了确保我们为网站使用专用空间,我们为其创建了一个虚拟环境。
为此,我们将使用virtualenv包。让我们先安装它,
Python −m pip install virtualenv
现在,为我们的网站创建一个文件夹,比如Django-intro。创建文件夹后,就可以在其中设置虚拟环境了。为此,请启动您的终端并以“cd”方式进入项目目录并使用命令
virtualenv env
这应该创建一个名为env的文件夹。为了进入这个虚拟环境,你必须使用命令
source env/bin/activate
如果您的环境名称带有括号,则您已成功进入虚拟环境。
入门
首先,请确保您已安装Python,版本3.6或更高版本。
接下来,使用Pip安装Django。
Python −m pip install Django
验证您的Django安装。
python −m Django version
而且,就是这样!您现在已经完成了让您的网站运行的初始阶段。现在让我们开始为网站创建我们的第一个应用程序!
创建应用程序
现在让我们获得开始所需的骨架。为此,请在虚拟环境中运行以下命令。
django−admin startproject Django−intro−app
这应该为Django应用程序创建一个基本框架。
如果你进入Django-intro-app文件夹,你可以看到它有一个manage.py文件和另一个同名的目录Django-intro-app和settings.py、urls.py和wsgi.py文件。
注意事项
Settings.py包含项目的所有各种设置。
Urls.py包含网站的所有不同路由。
我们构建的应用程序称为Django-intro-app。
我们为网站构建的每个后续应用程序都将位于主文件夹中并拥有自己的名称。
现在您了解了整个Django工作区的主要框架,让我们创建一个应用程序。
首先,`cd`到项目目录->Django-intro-app。
Pythonmanage.pystartapp first−app
现在应该创建一个名为first-app的目录,其中包含admin.py、apps.py、models.pytests.py和views.py文件夹中的文件。
接下来我们需要确保第一个应用程序被Django识别。为此,请转到Django-intro-app/settings.py并将first-app添加到INSTALLED_APPS部分。
这现在应该看起来像,
示例
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'howdy' ]
而且,就是这样!您现在已经创建了一个Django应用程序。为了测试我们的网络应用程序,让我们使用Django的网络服务器来运行它。
为此,请前往项目目录并使用命令
Pythonmanage.pyrunserver
如果您已完成上述所有操作,则您的网站应该在http://127.0.0.1:8000/上运行。打开链接并查看您自己的Django网页。
结论
您现在已经学会了设置一个虚拟环境来运行您的Python项目和Django应用程序。
您已经创建了自己的Django应用程序。显然,这还不是结束。您可以使用Html、CSS和JS为网站创建自己的模板。修改URL,链接各种页面并使用Django做更多事情!
有关Django系列的更多详细信息和信息,请在https://www.djangoproject.com/查看他们自己的文档。