본문 바로가기
카테고리 없음

Visual Studio의 Django 자습서 (2) Create a Django app with views and page templates

by EasyGPT 2023. 12. 19.
반응형

Step 2: Create a Django app with views and page templates

  • Article
  • 09/08/2023

In this article

  1. Step 2-1: Create an app with a default structure
  2. Step 2-2: Run the app from the Django project
  3. Step 2-3: Render a view using HTML
  4. Step 2-4: Render a view using a page template

Applies to:

Visual Studio

Visual Studio for Mac

Visual Studio Code

Previous step: Create a Visual Studio project and solution

Visual Studio 프로젝트에는, 1개 이상의 Django 을 실행할 수 있는 Django 프로젝트의 사이트 수준 구성요소만 있습니다.

다음 단계는 페이지가 1개인 첫째 앱을 만드는 것입니다.

In the Visual Studio project, you only have the site-level components of a Django project now, which can run one or more Django apps. The next step is to create your first app with a single page.

이 단계에서는 다음 방법을 알아봅니다:

In this step, you learn how to:

페이지 1개인 Django 앱 만들기 Create a Django app with a single page (step 2-1)

Django 프로젝트에서 앱 실행 Run the app from the Django project (step 2-2)

HTML을 사용하여 view 덴더 Render a view using HTML (step 2-3)

Django 페이지 템플릿을 사용, view 렌더 Render a view using a Django page template (step 2-4)

Step 2-1: Create an app with a default structure

기본 구조로 앱 만들기

Django앱은 특정 목적을 위한 관련 파일세트가 포함된 별도의 Python 패키지

Django 프로젝트에는 웹호스트가 단일 도메인이름에서 여러 별도의 진입점 제공하는 데 도움이 되는 많은 앱이 포함될 수 있습니다.

예를 들어 contoso.com 같은 도메인에 대한 Django 프로젝트에는

www.contoso.com용 앱 하나,

support.contoso.com용 두 번째 앱,

docs.contoso.com용 세 번째 앱이 포함될 수 있습니다.

A Django app is a separate Python package that contains a set of related files for a specific purpose. A Django project can contain many apps, which help a web host to serve many separate entry points from a single domain name. For example, a Django project for a domain like contoso.com might contain one app for www.contoso.com, a second app for support.contoso.com, and a third app for docs.contoso.com.

이 경우 Django 프로젝트는 사이트 수준 URL 라우팅 및 설정(urls.py 및 settings.py 파일에서)을 처리.

각 앱에는 내부라우팅, views, 모델, 정적 파일 및 관리 인터페이스를 통해 고유한 스타일과 동작​​이 있습니다.

Django 앱은 일반적으로 표준 파일세트로 시작.

VS는 동일한 목적을 수행하는 통합 메뉴명령과 함께 Django 프로젝트 내에서 Django 앱을 초기화하는 템플릿을 제공.

In this case, the Django project handles site-level URL routing and settings (in its urls.py and settings.py files). Each app has its own distinct styling and behavior through its internal routing, views, models, static files, and administrative interface.

A Django app usually begins with a standard set of files. Visual Studio provides templates to initialize a Django app within a Django project, along with an integrated menu command that serves the same purpose:

Templates

Solution Explorer에서 해당 프로젝트 (BasicProject)마우스오른쪽단추로 클릭하고 Add > New item을 선택.

Add New Item dialog에서 Django 1.9 App template을 선택하고 이름 필드에 앱 이름 (HelloDjangoApp)을 지정한 다음 Add를 선택.

In Solution Explorer, right-click the project and select Add > New item. In the Add New Item dialog, select the Django 1.9 App template, specify the app name in the Name field, and select Add.

통합명령: Solution Explorer에서 해당 프로젝트 (BasicProject)마우스오른쪽단추로 클릭하고 Add > Django app을 선택.

이 명령은 이름을 묻는 메시지를 표시.

New App Name에 앱 이름을 지정하고 OK를 선택.

Integrated command: In Solution Explorer, right-click the project and select Add > Django app. This command prompts you for a name. Specify the app name in the New App Name field, and select OK.

두 방법 중 하나를 사용, "HelloDjangoApp"이라는 이름의 앱을 만듦.

이제 프로젝트에 "HelloDjangoApp" 폴더가 생성되었음.

이 폴더에는 다음 항목이 포함되어 있음.

Using either method, create an app with the name "HelloDjangoApp". Now, the "HelloDjangoApp" folder is created in your project. The folder contains the following items:

 
Item
Description
migrations
Django가 모델 변경사항에 맞춰 데이터베이스를 업데이트하는 스크립트를 저장하는 폴더.
그런 다음 Django의 마이그레이션 도구는 현재 모델과 일치하도록 이전 버전의 데이터베이스에 필요한 변경사항을 적용.
마이그레이션을 사용하면 모델에 집중하고 Django가 기본 데이터베이스 스키마를 처리하게 할 수 있슴.
마이그레이션은 Django 문서에서 논의.
현재 폴더에는 __init__.py 파일이 포함되어 있슴(폴더가 자체 Python 패키지를 정의함을 나타냄).
A folder in which Django stores scripts that update the database to align with the changes to the models. Django's migration tools then apply the necessary changes to any previous version of the database to match the current models. Using migrations, you keep your focus on your models and let Django handle the underlying database schema. Migrations are discussed in the Django documentation. For now, the folder contains an __init__.py file (indicating that the folder defines its own Python package).
__init__.py
The file that identifies the app as a package.
templates
단일 index.html 파일이 포함된 Django 페이지 템플릿용 폴더. index.html 파일은 앱 이름과 동일한 폴더에 위치(VS 2017 15.7 이하에서는 파일이 템플릿 바로 아래에 배치되며 2-4단계에서는 하위 폴더를 만들도록 지시)
템플릿은 view가 페이지를 동적으로 렌더링하기 위해 정보를 추가할 수 있는 HTML 블록.
index.html의 {{ content }} 같은 페이지 템플릿 "변수"는 이 문서 뒷부분(2단계)에서 설명하는 동적 값에 대한 자리표시자.
일반적으로 Django 앱은 앱 이름과 일치하는 하위 폴더에 템플릿을 배치하여 템플릿에 대한 네임스페이스를 만듭니다.
A folder for Django page templates that contains a single index.html file. The index.html file is placed in the folder named same as the app name. (In Visual Studio 2017 15.7 and earlier, the file is placed directly under templates and step 2-4 instructs you to create the subfolder.) Templates are blocks of HTML into which views can add information to dynamically render a page. Page template "variables," such as {{ content }} in index.html, are placeholders for dynamic values as explained later in this article (step 2). Usually, Django apps create a namespace for their templates by placing them in a subfolder that matches the app name.
admin.py
The Python file in which you extend the app's administrative interface, which is used to view and edit data in a database. Initially, this file contains only the statement, from django.contrib import admin. By default, Django includes a standard administrative interface through entries in the Django project's settings.py file. To turn on the interface, you can uncomment the existing entries in urls.py file.
apps.py
앱의 구성 클래스를 정의하는 Python 파일(아래 표 뒤 참조). Python file that defines a configuration class for the app (see below, after this table).
models.py
Models are data objects, identified by functions, through which views interact with the app's underlying database. Django provides the database connection layer so that the apps don't concern themselves with the models details. The models.py file is a default place where you create your models. Initially, the models.py file contains only the statement, from django.db import models.
tests.py
A Python file that contains the basic structure of unit tests.
views.py
views는 HTTP 요청을 받아 HTTP 응답을 반환하는 웹페이지와 유사.
일반적으로 view는 HTML로 렌더되고 웹브라우저는 표시방법을 알고 있지만 view가 반드시 표시될 필요는 없슴(중간 형식처럼).
view는 HTML을 브라우저에 렌더하는 역할을 담당하는 Python 함수에 의해 정의됨.
views.py 파일은 view를 생성하는 기본 위치.
views.py 파일에는 from django.shortcuts import render 명령문만 포함되어 있슴(처음에는).
Views are similar to web pages, which take an HTTP request and returns an HTTP response. Usually, views render as HTML and the web browsers know how to display, but a view doesn't necessarily have to be visible (like an intermediate form). A view is defined by a Python function whose responsibility is to render the HTML to the browser. The views.py file is a default place where you create your views. Initially, the views.py file contains only the statement, from django.shortcuts import render.

"HelloDjangoApp"이라는 이름을 사용하면, apps.py 파일의 내용이 다음과 같이 나타납니다:

When you use the name "HelloDjangoApp," the contents of the apps.py file appears as:

Python

from django.apps import AppConfig

class HelloDjangoAppConfig(AppConfig):

name = 'HelloDjango'

https://amzn.to/4am7GoJ

 

Hasbro Gaming Clue: Disney Villains Edition Board Game for Kids Ages 8+, 2-6 Players (Amazon Exclusive)

Disney's most mischievous Villains team up to steal all the magic in the universe, but one crafty Villain is hiding something from the rest! Players need to figure out who that is, what magical item they stole, and where it's hidden. Play as Ursula, Gaston, Lady Tremaine, Dr. Facilier, Mother Got...

amzn.to

Question: Is creating a Django app in Visual Studio any different from creating an app on the command line?

Visual Studio에서 Django 앱을 만드는 것과 명령줄에서 앱을 만드는 것이 다른가요?

답변: Add > Django app command을 실행하거나 Django 앱 템플릿과 함께 Add > New Item을 사용하면 Django 명령manage.py startapp <app_name>과 동일한 파일이 생성됩니다.

Visual Studio에서 앱을 만들 때의 이점은 앱 폴더와 해당 파일이 모두 자동으로 프로젝트에 통합된다는 것입니다.

동일 VS 명령을 사용하여 프로젝트에 앱을 원하는 만큼 만들 수 있습니다.

Running the Add > Django app command or using Add > New Item with a Django app template produces the same files as the Django command manage.py startapp <app_name>. The benefit of creating an app in Visual Studio is that the app folder and all its files are automatically integrated in the project. You can use the same Visual Studio command to create any number of apps in your project.

Step 2-2: Run the app from the Django project

이 시점에서 VS에서 프로젝트를 다시 실행하면(도구 모음 단추 또는 Debug > Start Debugging 사용) 기본 페이지가 계속 표시됩니다.

앱별 페이지를 정의하고, Django 프로젝트에 앱을 추가해야 앱 콘텐츠가 표시됩니다.

At this point, if you run the project again in Visual Studio (using the toolbar button or Debug > Start Debugging), you'll still see the default page. No app content appears because you need to define an app-specific page and add the app to the Django project:

1. HelloDjangoApp 폴더에서 views.py 파일을 수정하여 "index"라는 view를 정의

In the HelloDjangoApp folder, modify the views.py file to define a view named "index":

Python

from django.shortcuts import render

from django.http import HttpResponse

def index(request):

return HttpResponse("Hello, Django!")

2. BasicProject 폴더(1단계에서 생성)에서 다음 코드와 일치하게 urls.py 파일을 수정(원하는 경우, 유익한 comment는 유지해도 됨).

In the BasicProject folder (created in step 1), modify the urls.py file to match the following code (you can keep the instructive comment, if you like):

from django.urls import include, re_path

import HelloDjangoApp.views

# Django processes URL patterns in the order they appear in the array

# Django는 배열에 나타나는 순서대로 URL 패턴을 처리

urlpatterns = [

re_path(r'^$', HelloDjangoApp.views.index, name='index'),

re_path(r'^home$', HelloDjangoApp.views.index, name='home')

]

각 URL 패턴은 Django가 특정 사이트-상대 URL(즉, https://www.domain.com/ 다음 부분)을 라우트하는 views를 설명.

Each URL pattern describes the views to which Django routes specific site-relative URLs (that is, the portion that follows https://www.domain.com/).

정규식 ^$로 시작하는 urlPatterns의 첫째 항목은 사이트 루트 "/"에 대한 라우팅.

The first entry in urlPatterns that starts with the regular expression ^$ is the routing for the site root, "/".

두 번째 항목 ^home$은 "/home"을 구체적으로 라우팅.

The second entry, ^home$ specifically routes "/home".

동일한 view에 대하여 경로를 여러개 가질 수 있습니다.

You can have multiple routings to the same view.

3. 프로젝트를 다시 실행하여 Hello, Django! 메시지를 확인하세요.

view에 의해 정의된 대로입니다.

완료되면 서버를 중지합니다.

Run the project again to see the message Hello, Django! as defined by the view. When you're done, stop the server.

https://smartstore.naver.com/dopza/products/4569179898

Commit to source control

소스제어에 커밋

코드 변경하고 성공적으로 테스트한 후에 소스제어를 검토하고 커밋할 수 있습니다.

이 자습서 이후 단계에서 소스제어에 다시 커밋하라는 메시지가 표시되면 이 섹션을 참조할 수 있습니다.

After making changes to your code and testing successfully, you can review and commit to the source control. In later steps, when this tutorial reminds you to commit to source control again, you can refer to this section.

1. Visual Studio 하단에 있는 변경단추(아래 원)를 선택하여 팀 탐색기로 이동.

Select the changes button along the bottom of Visual Studio (circled below), to navigate to Team Explorer.

팀 탐색기에서 "초기 Django 앱 만들기"와 같은 커밋 메시지를 입력하고 모두 커밋을 선택합니다.

커밋이 완료되면 로컬에서 생성된 Commit <hash> 메시지가 표시됩니다.

변경 사항을 서버와 공유하려면 동기화하세요.

변경 사항을 원격 리포지토리에 푸시하려면 동기화를 선택한 다음 나가는 커밋에서 푸시를 선택합니다.

원격으로 푸시하기 전에 여러 로컬 커밋을 누적할 수도 있습니다.

In Team Explorer, enter a commit message like "Create initial Django app" and select Commit All. When the commit is complete, you see a message Commit <hash> created locally. Sync to share your changes with the server. If you want to push changes to your remote repository, select Sync, and then select Push under Outgoing Commits. You can also accumulate multiple local commits before pushing to remote.

질문: 라우팅 문자열 앞의 'r' 접두사는 무엇입니까?

What is the 'r' prefix before the routing strings for?

답변: Python에서 문자열의 'r' 접두사는 "원시 raw"를 의미하며, 이는 Python이 문자열 내의 모든 문자를 이스케이프하지 않게 지시합니다.

정규식에는 많은 특수문자가 사용됩니다.

'r' 접두사를 사용하면 이스케이프 문자 '\'보다 문자열을 훨씬 쉽게 읽을 수 있습니다.

The 'r' prefix on a string in Python means "raw," which instructs Python to not escape any characters within the string. The regular expressions use many special characters. Using the 'r' prefix make the strings much easier to read than the escape characters '\'.

질문: URL 라우팅 항목에서 ^ 및 $ 문자는 무엇을 의미합니까?

What do the ^ and $ characters mean in the URL routing entries?

답변: URL 패턴을 정의하는 정규식에서, ^는 "줄 시작"을 의미하고 $는 "줄 끝"을 의미하는데, 여기서 URL은 사이트 루트에 상대적입니다 (https://www.domain.com 다음 부분)

In the regular expressions that define URL patterns, ^ means "start of line" and $ means "end of line," wherein the URLs are relative to the site root (the part that follows https://www.domain.com/).

정규식 ^$는 사실상 "공백"을 의미, 전체 URL https://www.domain.com/(사이트 루트에 추가된 항목 없음)과 일치.

^home$ 패턴은 https://www.domain.com/home/과 정확히 일치(Django는 패턴 일치에서 후행 /를 사용하지 않음)

The regular expression ^$ effectively means "blank" and matches the full URL https://www.domain.com/ (nothing added to the site root). The pattern ^home$ matches exactly https://www.domain.com/home/. (Django doesn't use the trailing / in pattern matching.)

^home 같이 정규식에서 후행 $를 사용하지 않으면 URL 패턴은 "home", "homework", "homestead", "home192837" 같이 "home"으로 시작하는 모든 URL과 일치.

다양한 정규식을 실험하려면 regex101.com at pythex.org 같은 온라인 도구를 사용.

If you don't use a trailing $ in a regular expression, as with ^home, then URL pattern matches any URL that begins with "home" such as "home", "homework", "homestead", and "home192837".

To experiment with different regular expressions, try online tools such as regex101.com at pythex.org.

https://amzn.to/3v3hXpI

 
 

L'OR Barista System Coffee and Espresso Machine Combo by Philips, Black

An all-in-one system designed with variety in mind. Create your own masterpiece in taste with the L'OR BARISTA system.

amzn.to

2-3단계: HTML을 사용하여 view 렌더하기

Render a view using HTML

views.py 파일에 있는 index 함수는 페이지에 대한 일반 텍스트 HTTP 응답을 생성.

대부분의 실제 웹페이지는 종종 라이브 데이터를 통합하는 풍부한 HTML 페이지로 응답.

실제로 함수를 사용하여 view를 정의하는 주된 이유는 콘텐츠를 동적으로 생성하기 위한 것입니다.

The index function that you have in views.py file generates a plain-text HTTP response for the page. Most real-world web pages respond with rich HTML pages that often incorporate live data. Indeed, the primary reason to define a view using a function is to generate the content dynamically.

HttpResponse에 대한 인수는 문자열이므로, 문자열 내에서 원하는 HTML을 작성할 수 있습니다.

간단한 예로 index 함수를 다음 코드로 바꿉니다(기존 from 문 유지).

그러면 index 함수는 페이지를 새로 고칠 때마다 업데이트되는 동적 콘텐츠를 사용하여 HTML 응답을 생성.

As the argument to HttpResponse is just a string, you can build up any HTML you like within a string. As a simple example, replace the index function with the following code (keep the existing from statements). The index function will then generate an HTML response using dynamic content that's updated every time you refresh the page.

Python

from datetime import datetime

def index(request):

now = datetime.now()

html_content = "<html><head><title>Hello, Django</title></head><body>"

html_content += "<strong>Hello Django!</strong> on " + now.strftime("%A, %d %B, %Y at %X")

html_content += "</body></html>"

return HttpResponse(html_content)

이제 프로젝트를 다시 실행하면 Hello Django! on Sunday, 17 December, 2023 at 21:21:27"과 같은 메시지가 표시됩니다.

페이지를 새로 고쳐 시간을 업데이트하고 각 요청에 따라 콘텐츠가 생성되는지 확인하세요.

완료되면 서버를 중지합니다.

Now, run the project again to see a message like "Hello Django! on Sunday, 17 December, 2023 at 21:21:27". Refresh the page to update the time and confirm that the content is being generated with each request. When you're done, stop the server.

Tip

프로젝트를 중지하고 다시 시작하는 바로가기는 Debug > Restart menu command (Ctrl+Shift+F5) 또는 debugging toolbar의 Restart button을 사용:

A shortcut to stopping and restarting the project is to use the Debug > Restart menu command (Ctrl+Shift+F5) or the Restart button on the debugging toolbar:

Step 2-4: Render a view using a page template

페이지 템플릿을 사용하여 view 렌더하기

코드에서 HTML 생성하는 것은 작은 페이지에서는 잘 작동합니다.

하지만 페이지가 점점 복잡해지면 페이지의 정적 static HTML 부분(CSS 및 JavaScript 파일에 대한 참조와 함께)을 "page templates"으로 유지해야 합니다.

그런데 코드로 생성된 동적 콘텐츠page templates에 삽입할 수 있습니다.

이전 섹션에서, now.strftime 호출의 날짜 및 시간만 동적이었는데, 이는 다른 모든 콘텐츠도 페이지 템플릿에 배치할 수 있음을 의미합니다.

Generating HTML in code works fine for small pages. However, as pages get more sophisticated you need to maintain the static HTML parts of your page (along with references to CSS and JavaScript files) as "page templates." You can then insert the dynamic, code-generated content to the page templates. In the previous section, only the date and time from the now.strftime call is dynamic, which means all the other content can be placed in a page template.

Django 페이지템플릿은, "변수"라는 이름의 여러 대체 토큰이 포함되는 HTML 블록.

변수는 {{ 및 }}로 구분됨(예: {{ content }}).

그런데 Django 템플릿모듈은 변수를 코드에서 제공하는 동적 콘텐츠로 바꿉니다.

A Django page template is a block of HTML that contains multiple replacement tokens called "variables." The variables are delineated by {{ and }}, for example, {{ content }}. Django's template module then replaces variables with dynamic content that you provide in code.

다음 단계는 페이지 템플릿 용도를 보여줍니다:

The following steps demonstrate the use of page templates:

Django 프로젝트가 포함된 BasicProject 폴더에서 settings.py 파일을 엽니다.

INSTALLED_APPS 목록에 앱 이름 "HelloDjangoApp"을 추가.

목록에 앱을 추가하면 앱이 포함된 "HelloDjangoApp" 이름의 폴더가 있음을 Django 프로젝트에 알립니다.

Under the BasicProject folder, which contains the Django project, open the settings.py file. Add the app name, "HelloDjangoApp," to the INSTALLED_APPS list. Adding the app to the list tells the Django project that there's a folder of "HelloDjangoApp" name containing an app:

Python

INSTALLED_APPS = [

'HelloDjangoApp',

# Other entries...

]

settings.py 파일에서 TEMPLATES 객체에 다음 줄(기본적으로 포함됨)이 포함되어 있는지 확인하세요.

다음 코드는 설치된 앱의 템플릿 폴더에서 템플릿을 찾도록 Django에 지시합니다.

In the settings.py file, ensure that the TEMPLATES object contains the following line (included by default). The following code instructs Django to look for templates in an installed app's templates folder:

JSON

'APP_DIRS': True,

HelloDjangoApp 폴더에서, template/HelloDjangoApp/index.html 페이지 템플릿 파일(또는 VS 2017 15.7 이하의 경우 template/index.html)을 열어 여기에 1개의 변수 {{ content }}가 포함되어 있는지 확인합니다.

In the HelloDjangoApp folder, open the templates/HelloDjangoApp/index.html page template file (or templates/index.html in VS 2017 15.7 and earlier), to observe that it contains one variable, {{ content }}:

HTML

<html>

<head>

<title></title>

</head>

<body>

{{ content }}

</body>

</html>

HelloDjangoApp 폴더에서 views.py 파일을 열고 index 함수를 django.shortcuts.render 도우미 함수를 사용하는 다음 코드로 바꿉니다.

render 도우미는 페이지 템플릿 작업을 위한 단순화된 인터페이스를 제공.

기존 from 문을 모두 유지해야 합니다.

In the HelloDjangoApp folder, open the views.py file and replace the index function with the following code that uses the django.shortcuts.render helper function. The render helper provides a simplified interface for working with page templates. Ensure that you keep all the existing from statements.

Python

from django.shortcuts import render # Added for this step

def index(request):

now = datetime.now()

return render(

request,

"HelloDjangoApp/index.html", # Relative path from the 'templates' folder to the template file

# "index.html", # Use this code for VS 2017 15.7 and earlier

{

'content': "<strong>Hello Django!</strong> on " + now.strftime("%A, %d %B, %Y at %X")

}

)

render 할 첫째 인수는 request 객체이고, 그 뒤에는 앱의 템플릿 폴더에 있는 템플릿 파일에 대한 상대 경로가 옵니다.

The first argument to render, is the request object, followed by the relative path to the template file within the app's templates folder.

템플릿 파일은, 해당하는 경우 지원하는 view에 따라 이름이 지정됩니다.

A template file is named for the view it supports, if appropriate.

render할 세 번째 인수는 템플릿이 참조하는 변수 사전입니다.

The third argument to render is then a dictionary of variables that the template refers to.

사전에 객체를 포함할 수 있는데, 이 경우 템플릿의 변수는 {{ object.property }}를 참조할 수 있습니다.

You can include objects in the dictionary, in that case a variable in the template can refer to {{ object.property }}.

프로젝트를 실행하고 출력을 관찰합니다.

템플릿이 작동한다는 것을 나타내는 2-2단계와 유사한 메시지가 표시되어야 합니다.

Run the project and observe the output. You should see a similar message as in step 2-2, indicating that the template works.

render 함수가 HTML을 자동으로 이스케이프하므로, content 속성에 사용한 HTML은 일반 텍스트로만 render 합니다.

Observe, that the HTML you used in the content property renders only as plain text because the render function automatically escapes the HTML.

Automatic escape는 주입 공격에 대한 우발적 취약성을 방지합니다.

개발자는 종종 한 페이지에서 입력을 수집하고 템플릿 자리표시자를 통해 다른 페이지의 값으로 사용합니다.

Automatic escape prevents accidental vulnerabilities to injection attacks. Developers often gather input from one page and use it as a value in another through a template placeholder.

이스케이프는 HTML을 페이지 템플릿에 유지하고 코드외부에 유지하는 것이 가장 좋다는 점을 상기시켜 주는 역할도 합니다.

또한 필요한 경우 더 많은 변수를 만드는 것도 간단합니다.

Escaping also serves as a reminder that it's best to keep the HTML in the page template and out of the code. Also, it's simple to create more variables where needed.

예를 들어, 다음 마크업과 일치되게 templates이 포함된 index.html 파일을 변경합니다.

다음 마크업은 페이지 제목을 추가하고 페이지 템플릿의 모든 서식을 유지합니다.

For example, change the index.html file with templates to match the following markup. The following markup adds a page title and keeps all the formatting in the page template:

HTML

<html>

<head>

<title>{{ title }}</title>

</head>

<body>

<strong>{{ message }}</strong>{{ content }}

</body>

</html>

그런 다음 페이지 템플릿의 모든 변수에 대한 값을 제공하려면 여기에 지정된 대로 index view function를 작성하세요:

Then, to provide values for all the variables in the page template, write the index view function as specified here:

Python

def index(request):

now = datetime.now()

return render(

request,

"HelloDjangoApp/index.html", # Relative path from the 'templates' folder to the template file

# "index.html", # Use this code for VS 2017 15.7 and earlier

{

'title' : "Hello Django",

'message' : "Hello Django!",

'content' : " on " + now.strftime("%A, %d %B, %Y at %X")

}

)

서버를 중지하고 프로젝트를 다시 시작하십시오.

페이지가 제대로 렌더링되는지 확인하세요.

Stop the server and restart the project. Ensure that the page renders properly:

Visual Studio 2017 버전 15.7 이하: 마지막 단계로 템플릿을 앱과 동일한 이름의 하위 폴더로 이동합니다.

하위 폴더는 네임스페이스를 생성하고 프로젝트에 추가할 수 있는 다른 앱과의 잠재적 충돌을 방지합니다. (VS 2017 15.8+의 템플릿은 이 작업을 자동으로 수행합니다.)

Visual Studio 2017 version 15.7 and earlier: As a final step, move your templates into a subfolder named the same as your app. The subfolder creates a namespace and avoids potential conflicts with other apps you might add to the project. (The templates in VS 2017 15.8+ do this for you automatically.)

즉, HelloDjangoApp 이라는 templates에 하위 폴더를 만들고 index.html 파일을 해당 하위 폴더로 이동한 다음 index view function을 수정합니다.

index view function는 템플릿의 새 경로인 HelloDjangoApp/index.html을 참조합니다.

그런 다음 프로젝트를 실행하고 페이지가 제대로 render하는지 확인한 후 서버를 중지합니다.

That is, create a subfolder in templates named HelloDjangoApp, move the index.html file into that subfolder, and modify the index view function. The index view function will refer to the template's new path, HelloDjangoApp/index.html. Then run the project, verify that the page renders properly, and stop the server.

2-2단계에 설명된 대로 변경사항을 소스제어에 커밋하고 필요한 경우 원격저장소를 업데이트합니다.

Commit your changes to source control and update your remote repository, if needed, as described under step 2-2.

Question: Do page templates have to be in a separate file?

페이지 템플릿은 별도의 파일에 있어야 합니까?

답변: 일반적으로 템플릿은 별도의 HTML 파일로 유지됩니다.

인라인 템플릿을 사용할 수도 있습니다.

마크업과 코드를 깔끔하게 분리하려면 별도의 파일을 사용하는 것이 좋습니다.

Usually, templates are maintained in separate HTML files. You can also use an inline template. To maintain a clean separation between markup and code, using a separate file is recommended.

질문: 템플릿은 .html 파일 확장자를 사용해야 합니까?

Question: Templates must use the .html file extension?

답변: 페이지 템플릿 파일의 .html 확장자는 완전히 선택사항.

render함수에 대한 두 번째 인수에서 파일의 정확한 상대경로를 식별하기 때문입니다.

그러나 Visual Studio(및 기타 편집기)는 .html 파일을 사용하여 코드 완성 및 구문 색상 지정과 같은 기능을 제공하며 이는 페이지 템플릿이 HTML이 아니라는 사실보다 중요합니다.

실제로 Django 프로젝트로 작업할 때 Visual Studio는 Django 템플릿이 있는 HTML 파일을 자동으로 감지하고 특정 자동 완성 기능을 제공합니다.

예를 들어 Django 페이지 템플릿 주석 {#을 입력하기 시작하면 Visual Studio에서 자동으로 닫는 #} 문자를 제공합니다.

Comment SelectionUncomment Selection commands (편집 > 고급 메뉴 및 도구 모음에 있음)도 HTML 주석 대신 템플릿 주석을 사용합니다.

The .html extension for page template files is entirely optional, as you identify the exact relative path to the file in the second argument to the render function. However, Visual Studio (and other editors) provides the features like code completion and syntax coloration with .html files, which outweighs the fact that the page templates aren't strictly HTML.

In fact, when you're working with a Django project, Visual Studio automatically detects the HTML file that has a Django template and provides certain autocomplete features. For example, when you start typing a Django page template comment, {#, Visual Studio automatically gives you the closing #} characters. The Comment Selection and Uncomment Selection commands (on the Edit > Advanced menu and on the toolbar) also use the template comments instead of HTML comments.

질문: 프로젝트 실행 때 템플릿을 찾을 수 없다는 오류가 표시됩니다. 뭐가 문제지요?

When I run the project, I see an error that the template can't be found. What's wrong?

답변: 템플릿을 찾을 수 없다는 오류가 표시되면 INSTALLED_APPS 목록의 Django 프로젝트 settings.py에 앱을 추가했는지 확인하세요.

해당 항목이 없으면 Django는 앱의 templates folder에서 무엇을 찾아야 할지 알 수 없습니다.

If you see errors that the template can't be found, ensure that you've added the app to the Django project's settings.py in the INSTALLED_APPS list. Without that entry, Django won't know what to look in the app's templates folder.

질문: 템플릿 네임스페이스가 왜 중요한가요?

Why is template namespacing important?

답변: Django는 render 함수에서 참조되는 템플릿을 찾을 때 상대경로와 일치하는 첫 번째 파일을 사용합니다.

동일한 프로젝트에 동일한 템플릿 폴더 구조를 가진 여러 Django 앱이 있는 경우 한 앱이 의도치 않게 다른 앱의 템플릿을 사용할 가능성이 있습니다.

이러한 오류를 방지하려면 항상 앱 이름과 일치하는 앱의 템플릿 폴더 아래에 하위 폴더를 만들어 중복을 피하세요.

When Django looks for a template referred to in the render function, it uses the first file that matches the relative path. If you have multiple Django apps in the same project with same folder structures for templates, it's likely that one app will unintentionally use a template from another app. To avoid such errors, always create a subfolder under an app's templates folder that matches the name of the app to avoid any duplication.

Next steps

Serve static files, add pages, and use template inheritance

Go deeper

https://amzn.to/3vaLMo5

 
반응형

댓글