본문 바로가기
Django11

Getting Started with Django

by 자동매매 2023. 4. 8.

Django overview

 

Django Home  https://www.djangoproject.com/

 

 

Django uses the MVT (Model-View-Template) pattern, which is slightly similar to MVC (Model-View-Controller) pattern.

The MVT pattern consists of three main components:

  • Model – defines the data or contains the logic that interacts with the data in the database.
  • View – communicates with the database via model and transfers data to the template for representing the data.
  • Template – defines the template for displaying the data in the web browser.

Django 프레임워크 자체가 컨트롤러 역할을 합니다. Django 프레임워크는 요청을 적절한 보기로 보내는 URL 패턴을 사용합니다.

실제로는 Django 애플리케이션에서 모델, 템플릿, 보기 및 URL로 작업하는 경우가 많습니다.

 

Django architecture

 

 

  • 웹 브라우저는 URL로 페이지를 요청하고 웹 서버는 HTTP 요청을 Django에 전달합니다.
  • Django는 URL을 URL 패턴과 일치시켜 첫 번째 일치 항목을 찾습니다.
  • Django는 일치하는 URL에 해당하는 보기를 호출합니다.
  • 보기는 모델을 사용하여 데이터베이스에서 데이터를 검색합니다.
  • 모델은 데이터를 뷰에 반환합니다.
  • 뷰는 템플릿을 렌더링하고 이를 HTTP 응답으로 반환합니다.

 

Creating a virtual environment

A virtual environment creates an isolated environment that consists of an independent set of Python packages.

By using virtual environments, you can have projects that use different versions of Django. Also, when you move the project to a different server, you can install all the dependent packages of the project using a single pip command.

 

First, create a new directory django-playground:

mkdir django-playground

Second, navigate to the django-playground directory:

cd django-playground

Third, create a new virtual environment using the venv module:

python -m venv venv

Fourth, activate the virtual environment:

venv\scripts\activate

The terminal will show the following:

(venv) D:\django-playground>

Note that you can deactivate the virtual environment using the deactivate command:

deactivate

 

Install the Django package

First, issue the following pip command to install the Django package:

pip install django

Second, check the Django version:

python -m django --version

It’ll show something like this:

4.2

Note that you likely see a higher version.

 

Exploring Django commands

Django comes with a command-line utility program called django-admin that manages administrative tasks such as creating a new project and executing the Django development server.

To run the Django, you execute the following command to list all Django core commands:

 

command-line utility program - 새 프로젝트 생성 및 Django 개발 서버 실행과 같은 관리 작업을 관리

실행 파일 : django-admin.exe

 

Django를 실행하려면 다음 명령을 실행하여 모든 Django 핵심 명령을 나열합니다.

django-admin

Output:

Type 'django-admin help <subcommand>' for help on a specific subcommand.

Available subcommands:

[django]
    check
    compilemessages
    createcachetable
    dbshell
    diffsettings
    dumpdata
    flush
    inspectdb
    loaddata
    makemessages
    makemigrations
    migrate
    optimizemigration
    runserver
    sendtestemail
    shell
    showmigrations
    sqlflush
    sqlmigrate
    sqlsequencereset
    squashmigrations
    startapp
    startproject
    test
    testserver

 

Django project 생성

For now, we’re interested in the startproject command that creates a new Django project. The following startproject command creates a new project called django_project:

django-admin startproject django_project C:\django-playground

This command creates a django_project directory. Let’s explore the project structure.

cd django_project

The following shows the django_project structure:

├── django_project
| ├── asgi.py
| ├── settings.py
| ├── urls.py
| ├── wsgi.py
| └── __init__.py
└── manage.py

 

다음은 Django 프로젝트의 각 파일에 대한 간략한 개요입니다.

  • manage.py  프로젝트와 상호 작용하는데 사용하는 명령줄 프로그램(예, 개발 서버 시작 및 데이터베이스 변경)

django_project 이 포함하는 파일 :

  • __init__.py  디렉토리가 패키지임을 나타내는 빈 파일입니다 .
  • settings.py – project settings ( 예,  installed applications, database connections, template directories )
  • urls.py         – URL을 view에 매핑하는 경로 목록을 저장
  • wsgi.py         – WSGI 프로젝트를 실행하는 환경을 포함  
  • asgi.py     –  AWSGI 프로젝트를 실행하는 환경을 포함

 

Running the Django development server

 

Django에는 개발 목적으로 Django 프로젝트를 빠르게 실행할 수 있는 웹 서버가 내장되어 있습니다.

Django 개발 웹 서버는 지속적으로 코드 변경 사항을 확인하고 프로젝트를 자동으로 다시 로드합니다. 그러나 프로젝트에 새 파일을 추가하는 것과 같은 일부 경우에는 웹 서버를 수동으로 다시 시작해야 합니다.

 

python manage.py runserver

Output:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
...
Django version 4.1.1, using settings 'django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

 

Once the server is up and running, you can open the web app using the URL listed in the output. Typically, the URL is something like this:

http://127.0.0.1:8000/

Now, you can copy and paste the URL to a web browser. It should show the following webpage:

The urls.py contains a default route that maps /admin path with the admin.site.urls view:

from django.contrib import admin
from django.urls import path

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

 

 

To open the admin page, you use the following URL:

http://127.0.0.1:8000/admin

It’ll show a login page:

 

Stop the Django development server

Ctrl + C twice.

 

Create requirements.txt file

 

The requirements.txt file contains all dependencies for a specific Django project. It also contains the dependencies of dependencies.

To create a requirements.txt file, you run the following pip command:

pip freeze > requirements.txt

When you move the project to a new server e.g., a test or production server, you can install all the dependencies used by the current Django project using the following pip command:

pip install -r requirements.txt

 

Summary

 

  • Django는 웹 애플리케이션을 빠르게 개발할 수 있게 해주는 Python 웹 프레임워크입니다.
  • Django는 MVC(Model-View-Controller) 패턴과 유사한 MVT(Model-View-Template) 패턴을 사용합니다.
  • 새 프로젝트를 만들기 -  django-admin startproject new_project 
  • 웹 서버를 사용하여 프로젝트를 실행 -  python manage.py runserver 
  • 웹 서버를 중지-  Ctrl+C

'Django11' 카테고리의 다른 글

Django Migrations  (0) 2023.04.28
Django Models  (0) 2023.04.28
Django 배포  (0) 2023.04.14
Django Create App  (0) 2023.04.08
[ DJANGO ] Index  (0) 2023.04.08

댓글