[Django]Create a hello-world App

2018-09-18  本文已影响0人  SharlotteZZZ

Versions:

Step 1 Create your folder and python file
.../hello-world/hello.py

Step 2 Three Required Django Settings

import sys
from django.conf import settings 

settings.configure(
    DEBUG=True,
    SECRET_KEY='thisisabadkeybutitwilldo',
    ROOT_URLCONF=sys.modules[__name__],
)

Step 3 Configure the URL

urlpatterns variable is a list of URL patterns. Here, we're creating just one pattern, /hello-world/

from django.conf.urls import patterns
urlpatterns = patterns('',
    (r'^hello-world/$', index),
)

Django1.10以后的版本已经不再引入patterns了

from django.conf.urls import url
urlpatterns = [url(r'^hello-world/$', index, name='index'),]

Step 4 Configure the View

You'll notice that after the /hello-world/ URL is the word index. That's the name of the view that we need to create. Views are Python functions (can be Python classes as well) that are executed when a certain URL is accessed. In our sample application we now need to create a Python function named index.

from django.http import HttpResponse
def index(request):
    return HttpResponse('Hello, World')

Step 5 Enable Command Line Support

Django comes with a utility called execute_from_command_line that can be used to run the development web server from the command line. In this step we'll add a little bit of code that will tell our application that if this file is the main script file, it should use the execute_from_command_line utility.

from django.core.management import execute_from_command_line

if __name__ == "__main__":
    execute_from_command_line(sys.argv)

Putting all thing together, the hello.py should be like this:

import sys
from django.conf import settings
from django.conf.urls import url
from django.http import HttpResponse
from django.core.management import execute_from_command_line

settings.configure(
    DEBUG = True,
    SECRET_KEY = 'thisisabadkeybutitwilldo',
    ROOT_URLCONF = sys.modules[__name__],
)

def index(request):
    return HttpResponse('Hello, World')


urlpatterns = [url(r'^hello-world/$', index, name='index'),]

if __name__ == "__main__":
    execute_from_command_line(sys.argv)

Last step -- Go to your terminal, navigate to the hello-world folder, and make sure the virtual env is activated. Then run the following command. When you run this command you'll see a warning message. You can ignore that for now.

System check identified no issue
September 05, 2018 - 16:02:52
Django version 1.11.3, using settings None
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

Go to a web browser and access this URL: http://127.0.0.1:8000/hello-world/. The worlds 'Hello, World' should display.

上一篇下一篇

猜你喜欢

热点阅读