[Python] 1-4. Python Django Project APP Creation - Hello World!! (장고 프로젝트 Hello Word 띄우기)

2018. 9. 19. 16:11Programing/Python-Django

1. python manage.py startapp <app name>



2. Modify code and add new code as below.

Basically we’re saying whenever the view function homePageView is called, return the text “Hello, World!” More specifically, we’ve imported the built-in HttpResponse method so we can return a response object to the user. Our function homePageView accepts the request object and returns a response with the string Hello, World!


- a Python regular expression for the empty string ''

- specify the view which is called homePageView

- add an optional url name of 'home'

In other words, if the user requests the homepage, represented by the empty string '' then use the view called homePageView.


We’ve imported include on the second line next to path and then created a new urlpattern for our pages app. Now whenever a user visits the homepage at / they will first be routed to the pages app and then to the homePageView view.

It’s often confusing to beginners that we don’t need to import the pages app here, yet we refer to it in our urlpattern as pages.urls. The reason we do it this way is that that the method django.urls.include() expects us to pass in a module, or app, as the first argument. So without using include we would need to import our pages app, but since we do use include we don’t have to at the project level!


3. \mysite>python manage.py runserver

4. Browser - 127.0.0.1:8000

  

[Code]

#D:\Python\mysite\mysite\urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('apphello.urls')),
]


#D:\Python\mysite\apphello\urls.py
from django.urls import path

from .views import homePageView

urlpatterns = [
    path('', homePageView, name='home')
]


#D:\Python\mysite\apphello\views.py
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse


def homePageView(request):
    return HttpResponse('Hello, World!')