django新建一个项目_如何使用Django创建项目

django新建一个项目

Now that we know how to create virtual environments and use pip, we can begin building our project. In this article, we will create our first Django project, write tests, and start our development server.

既然我们知道如何创建虚拟环境和使用pip,我们就可以开始构建项目了。 在本文中,我们将创建我们的第一个Django项目,编写测试,并启动我们的开发服务器。

创建虚拟环境 (Creating the Virtual Environment)

First, let’s create a new virtual environment for this project. (If you haven’t already, deactivate the previous virtualenv by typing deactivate in the terminal). For more info on virtual environments and how to use them, visit this page.

首先,让我们为该项目创建一个新的虚拟环境。 (如果尚未deactivate ,请在终端中键入deactivate以前的virtualenv)。 有关虚拟环境及其使用方法的更多信息,请访问此页面 。

Navigate to the directory where you want the Django project and type the following into the terminal:

导航到您想要Django项目的目录,然后在终端中输入以下内容:

mkvirtualenv taskplanner --python=/usr/bin/python3

You may have to change your Python path if it looks different than the one above.

如果看起来与上述路径不同,则可能需要更改Python路径。

The command line shell should now look like below, indicating you are in a virtual environment.

现在,命令行外壳应如下所示,表明您处于虚拟环境中。

(taskplanner)<a href='https://sites.google.com/a/chromium.org/chromedriver/downloads' target='_blank' rel='nofollow'>munsterberg@Lenovo ~/workspace] $

If it doesn’t look like that, just type:

如果不是这样,只需键入:

workon taskplanner

We can now install Django:

我们现在可以安装Django:

pip install Django

创建我们的Django项目 (Create our Django Project)

With Django installed we can create our project:

安装Django之后,我们可以创建项目:

django-admin.py startproject taskplanner

Next, navigate into our new project by typing:

接下来,通过键入以下内容导航到我们的新项目:

cd taskplanner

Before we do anything, let’s set this directory as our working directory using virtualenvwrapper:

在做任何事情之前,让我们使用virtualenvwrapper将此目录设置为我们的工作目录:

setvirtualenvproject

Sidenote: For a list of virtualenvwrapper commands, type virtualenvwrapper into your terminal.

旁注 :有关virtualenvwrapper命令的列表,请在终端中键入virtualenvwrapper

Now, when we are in our virtual environment, we can type cdproject to navigate straight to our working directory.

现在,当我们处于虚拟环境中时,我们可以键入cdproject直接导航到我们的工作目录。

Your project directory should look something like this:

您的项目目录应如下所示:

taskplanner // our main working directory
|--- manage.py // similar to the django-admin script, you will see this used a
               // lot throughout our project
|--- taskplanner
    |--- __init__.py // this just tells python to treat this directory as a package
    |--- settings.py // main configuration file for our project
    |--- urls.py // we will use this to configure urls
    |--- wsgi.py // this is used for deploying our project to a production server

功能测试 (Functional Testing)

Test-driven development is a widely used best practice in developing software. Bascially, we want to write a test first that is bound to fail, and then write the least amount of code possible to pass that test. With Django, our goal is to write both functional tests (also known as; integration tests, end-to-end tests, etc.), and unit tests throughout development. Don’t sweat it, testing isn’t as difficult as it seems!

测试驱动的开发是软件开发中广泛使用的最佳实践。 基本上,我们想先编写一个注定会失败的测试,然后再编写最少可能通过该测试的代码。 使用Django,我们的目标是编写功能测试(也称为集成测试,端到端测试等)和整个开发过程中的单元测试。 不要流汗,测试并不像看起来那样困难!

But first, we need to create a new virtual environment dedicated to testing. Open a new tab in your terminal, navigate to your taskplanner project directory and type:

但是首先,我们需要创建一个专用于测试的新虚拟环境。 在终端中打开一个新选项卡,导航到taskplanner项目目录并键入:

mkvirtualenv taskplanner_test --python=/usr/bin/python3

Now you should have 2 tabs open in your terminal, one in the (taskplanner) virtual environment, and the other in the (taskplanner_test) virtual environment.

现在,您应该在终端中打开2个标签,一个在(taskplanner)虚拟环境中打开,另一个在(taskplanner_test)虚拟环境中打开。

If you type pip freeze in our new testing environment (taskplanner_test), you will notice nothing appears. This is because we have yet to install anything in our new environment.

如果您在我们的新测试环境(taskplanner_test)中输入pip freeze Frozen,您将不会看到任何内容。 这是因为我们尚未在新环境中安装任何东西。

So let’s go ahead and install Django first into our testing environment (taskplanner_test):

因此,让我们继续并将Django首先安装到我们的测试环境(taskplanner_test)中:

pip install Django

To create our functional tests we are going to need a few things. First, we need to have the Firefox web browser installed in our machine. If you don’t have Firefox, install that now.

要创建功能测试,我们需要做一些事情。 首先,我们需要在计算机上安装Firefox Web浏览器。 如果您没有Firefox,请立即安装。

Sidenote: You can use Chrome for integration testing, but you have to download the driver here and follow this stack overflow question. Firefox has had historically better performance than chrome when running integration tests, which is a very important consideration since compared to unit tests, integration tests are extremely slow.

旁注 :您可以使用Chrome进行集成测试,但必须在此处下载驱动程序然后遵循此堆栈溢出问题 。 从历史上看,Firefox在运行集成测试时具有比chrome更好的性能,这是一个非常重要的考虑因素,因为与单元测试相比,集成测试非常慢。

This is because integration tests are testing the entire system, rather than ‘units’ (small components). In the real world, sometimes it’s best to avoid integration tests because of the long development time to create them, slow run time, ambiguous errors, and other reasons you would discover in time.

这是因为集成测试正在测试整个系统,而不是“单元”(小型组件)。 在现实世界中,有时最好避免集成测试,因为创建它们的开发时间长,运行时间慢,模棱两可的错误以及您会及时发现的其他原因。

However, they are still worth our consideration when developing a real world app, and can be very useful in terms of reliability despite the performance downsides.

但是,在开发实际应用程序时,它们仍然值得我们考虑,尽管性能有所下降,但在可靠性方面仍然非常有用。

Next, we need to install a package called Selenium. This package will provide us with a WebDriver so we can control a browser with our tests. Selenium is usually used to automate your browser.

接下来,我们需要安装一个名为Selenium的软件包。 该软件包将为我们提供WebDriver,以便我们可以通过测试控制浏览器。 Selenium通常用于自动化浏览器。

pip install selenium

Now that we have that installed, we will need a directory to create our tests:

现在已经安装了该目录,我们将需要一个目录来创建测试:

mkdir functional_tests

In the taskplanner directory you should now see the following:

现在,在taskplanner目录中,您应该看到以下内容:

taskplanner
|-- functional_tests
|--- manage.py
|--- taskplanner
    ...

We now need to create a few files in our functional_tests folder. We will create an __init__.py file (this will tell python to treat functional_tests like a package), and a test_all_users.py file to contain our tests.

现在,我们需要在functional_tests文件夹中创建一些文件。 我们将创建一个__init__.py文件(这将告诉python将functional_tests像一个包一样对待)和一个test_all_users.py文件来包含我们的测试。

Let’s do that now:

现在开始:

touch functional_tests/__init__.py
touch functional_tests/test_all_users.py

Sidenote: __init__.py is almost always an empty file. For more info on what it’s used for, see this stackoverflow answer.

旁注__init__.py几乎总是一个空文件。 有关其用途的更多信息,请参见以下stackoverflow答案。

We can finally start writing our first functional test! Functional tests are for testing chunks of functionality in our web application. TDD with Python describes functional tests as “how the application functions from the user’s point of view”.

我们终于可以开始编写我们的第一个功能测试了! 功能测试用于测试我们的Web应用程序中的功能块。 使用Python的TDD将功能测试描述为“从用户的角度来看应用程序如何运行”。

So let’s open the test_all_users.py file in our text editor. First, we want to import selenium’s webdriver, and to make this a lot easier, Django provides something known as StaticLiveServerTestCase for live testing. Let’s import both of those now:

因此,让我们在文本编辑器中打开test_all_users.py文件。 首先,我们要导入selenium的webdriver,并且要使其变得更容易,Django提供了称为StaticLiveServerTestCase的功能来进行实时测试。 让我们现在导入这两个:

from selenium import webdriver
from django.contrib.staticfiles.testing import StaticLiveServerTestCase

Since we are testing from the users perspective, let’s name these tests NewVisitorTest. Add the following:

由于我们是从用户角度进行测试的,因此我们将这些测试命名为NewVisitorTest。 添加以下内容:

class NewVisitorTest(StaticLiveServerTestCase):
    def setUp(self):
        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(2)

    def tearDown(self):
        self.browser.quit()

First, we create a StaticLiveServerTestCase class named NewVisitorTest, this will contain our tests that we want to run for a new visitor. Then, we have two methods named setUp and tearDown. The setUp method is initialized when we run our tests. So, for each test we run, we open Firefox and wait 2 seconds for the page to load. tearDown runs after each test is finished, this method closes the browser for us after each test.

首先,我们创建一个名为NewVisitorTest的StaticLiveServerTestCase类,它将包含我们要为新访客运行的测试。 然后,我们有两个名为setUp和tearDown的方法。 运行测试时,将初始化setUp方法。 因此,对于我们运行的每个测试,我们都将打开Firefox并等待2秒钟以加载页面。 tearDown在每次测试完成后运行,此方法在每次测试后为我们关闭浏览器。

Now we can write our first test, and have Firefox open and close automatically for us. Let’s write our test now below the tearDown method.

现在,我们可以编写我们的第一个测试,并为我们自动打开和关闭Firefox。 现在让我们在tearDown方法下面编写测试。

def test_home_title(self):
        self.browser.get('http://localhost:8000')
        self.assertIn('Welcome to Django', self.browser.title)

Our first test, how exciting! Let’s walk through it. Every test we want to create must start with ‘test’. For example, if I wanted to create a test for my css, I would call the method test_h2_css. So here, we named the test test_home_title. That’s pretty self-explanatory, which is exactly what we want for our tests. The method first brings Firefox to the url http://localhost:8000, and then it checks if ‘Welcome to Django’ is in the html head tags title.

我们的第一个测试,多么令人兴奋! 让我们来看一看。 我们要创建的每个测试都必须以“ test”开头。 例如,如果要为CSS创建测试,则可以调用方法test_h2_css 。 因此,在这里,我们将测试命名为test_home_title 。 这是不言而喻的,这正是我们测试所需要的。 该方法首先将Firefox带到URL http://localhost:8000 ,然后检查html head标签标题中是否有“ Welcome to Django”。

Let’s run this test now and see what happens:

现在让我们运行此测试,看看会发生什么:

python manage.py test functional_tests

First, what exactly are we typing here? The manage.py script provides us with something called ‘test’, we will use this to run all of our tests. Here we are running it on our functional_tests package that we created with the __init__.py file.

首先,我们到底在这里键入什么? manage.py脚本为我们提供了一个称为“测试”的东西,我们将使用它来运行所有测试。 在这里,我们在使用__init__.py文件创建的functional_tests包中运行它。

After running this you should see something like the following in your terminal:

运行此命令后,您应该在终端中看到类似以下的内容:

F
======================================================================
FAIL: test_home_title (functional_tests.test_all_users.NewVisitorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/username/url/to/project/taskplanner/functional_tests/test_all_users.py", line 15, in test_home_title
    self.assertIn('Welcome to Django', self.browser.title)
AssertionError: 'Welcome to Django' not found in 'Problem loading page'

----------------------------------------------------------------------
Ran 1 test in 4.524s

FAILED (failures=1)

So it failed, but it gave us some handy advice. First, the AssertionError. ‘Welcome to Django’ not found in ‘Problem loading page’. So that means the title of http://localhost:8000 was ‘Problem loading page’. If you navigate to the url, you will see that the web page was not available.

因此失败了,但是它给了我们一些方便的建议。 首先,AssertionError。 在“问题加载页面”中找不到“欢迎使用Django”。 因此,这意味着http://localhost:8000的标题为“问题加载页面”。 如果导航到该URL,您将看到该网页不可用。

Let’s try running our Django server to get the test to pass. Switch back to the terminal tab that is in the taskplanner virtual environment and run our server.

让我们尝试运行Django服务器以使测试通过。 切换回taskplanner虚拟环境中的终端选项卡,然后运行我们的服务器。

python manage.py runserver

You should see something like the following:

您应该看到类似以下内容:

Performing system checks...

System check identified no issues (0 silenced).

You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.

March 06, 2016 - 20:53:38
Django version 1.9.4, using settings 'taskplanner.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Don’t worry about the unapplied migrations message yet.

不必担心尚未应用的迁移消息。

Now that we have a server running on http://localhost:8000, lets run our test again.

现在,我们已经在http://localhost:8000上运行了服务器,让我们再次运行测试。

Go back to the other terminal tab that is in the taskplanner_test virtual environment and run the following once more:

返回到taskplanner_test虚拟环境中的另一个终端选项卡,然后再次运行以下命令:

python manage.py test functional_tests

You should see the following.

您应该看到以下内容。

Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 4.033s

OK
Destroying test database for alias 'default'...

到目前为止我们所做的 (What We’ve Done So Far)

Our first passing test!

我们的第一个通过测试!

We’ve covered a lot in this article. We created our first project, set up virtual environments for both development and testing purposes, wrote our first functional test, and followed the Test-driven development process by writing a failing test, and then making it making it pass.

我们在本文中介绍了很多内容。 我们创建了第一个项目,为开发和测试目的设置了虚拟环境,编写了我们的第一个功能测试,并通过编写失败的测试,然后使其通过来遵循测试驱动的开发过程。

使用入门模板 (Using starter templates)

You can save yourself a lot of time by kickstarting your project with a django starter template. These projects use best practices that will save you headaches later when your project grows. Some of the more popular projects are

通过使用django入门模板启动项目,可以节省很多时间。 这些项目使用最佳实践,可以在项目成长时为您省去烦恼。 一些比较受欢迎的项目是

翻译自: https://www.freecodecamp.org/news/how-to-create-a-project-with-django/

django新建一个项目

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值