Notice
Recent Posts
Recent Comments
관리 메뉴

안까먹을라고 쓰는 블로그

[DJango] 기초 튜토리얼 (feat, Visual Studio Code) 본문

Language/Python

[DJango] 기초 튜토리얼 (feat, Visual Studio Code)

YawnsDuzin 2020. 3. 30. 17:26

 

반응형

https://code.visualstudio.com/docs/python/tutorial-django

 

Python and Django tutorial in Visual Studio Code

Python Django tutorial demonstrating IntelliSense, code navigation, and debugging for both code and templates in Visual Studio Code, the best Python IDE.

code.visualstudio.com


 파이썬 설치

https://www.python.org/downloads/windows/

 

Python Releases for Windows

The official home of the Python Programming Language

www.python.org

 

 개발 IDE 설치 (Visual Studio Code 설치)

https://code.visualstudio.com/download

 

Download Visual Studio Code - Mac, Linux, Windows

Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows. Download Visual Studio Code to experience a redefined code editor, optimized for building and debugging modern web and cloud applications.

code.visualstudio.com

 

 

장고 설치
python -m pip install django
장고 버전 확인하기
python -m django --version

커맨드 입력

 

장고 프로젝트 만들기
django-admin startproject mysite

커맨드 입력
DJango 사이트 구조

더보기
  • 외부 mysite - 프로젝트의 컨테이너 입니다. 장고에게는그 이름이 중요하지 않습니다. 원하는 이름으로 바꿀 수 있습니다.

  • 내부 mysite - 프로젝트의 실제 파이썬 패키지 입니다. 그 이름은 그 안에 무엇이든 가져오기 위해 사용해야 하는  python 패키지 이름입니다. (예:) mysite.urls

  • mysite/__init__.py - 이 디렉토리를 파이썬 패키지로 간주해야 한다는 것을 파이썬에게 알려주는 빈 파일. 

  • mysite/settings.py - 이 장고 프로젝트의 설정/구성

  • mysite/urls.py - 이 장고 프로젝트의 URL선언

  • mysite/wsgi.py - WSGI 호환 웹 서버가 프로젝트를 제공하기 위한 진입 점입니다.

  • manage.py - 이 장고 프로젝트와 다양한 방식으로 상호 작용할 수 있는 명령 줄 유틸리티입니다.

 

장고 서버 실행

 - 외부 mysite 경로에서 아래의 명령문을 실행

python manage.py runserver						# 127.0.0.1:8000

python manage.py runserver 5000					# 127.0.0.1:5000
python manage.py runserver 192.168.0.10:5000	# 192.168.0.10:5000

커맨드 입력
초기 접속 화면


 

 

장고 앱 만들기

 - 외부 mysite 경로에서 아래의 명령문을 실행

  1. 프로젝트 - 특정 웹 사이트에 대한 구성 및 앱 모음입니다. 프로젝트에는 여러 앱이 포함될 수 있습니다

  2. 앱 - 웹 로그 시스템, 공개 레코드 데이터베이스 또는 간단한 설문 조사 앱과 같은 작업을 수행하는 웹 애플리케이션

python manage.py startapp polls

커맨드 입력
앱 생성화면

더보기
  • polls/models.py - 모델(기본적으로 데이터베이스 레이아웃)을 정의한다.
  • polls/urls.py - views.py의 정보를 url에 매핑을 구현 (라우팅)

  • polls/views.py - 화면에 표시되는 부분을 구현

 

Ex) polls/views.py

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

Ex) polls/urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

Ex) mysite/urls.py

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

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

 

 

 

 

Ex) polls/models.py

https://docs.djangoproject.com/en/2.1/intro/tutorial02/

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

 

models.py를 작성하고, 아래의 명령을 실행하면, 실제 DB정보를 자동으로 생성 및 수정해준다.

python manage.py makemigrations
python manage.py migrate

 

 


앱 등록

settings.py 의 INSTALLED_APPS 항목에 추가해 준다.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello',
]

 

 

 

TEMPLATES, STATICFILES 의 패스 변경

settings.py 의 TEMPLATES항목의 DIRS항목 변경

이거는 app을 하나만 쓸때 변경해 준다.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        # 'DIRS': [],
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

 

settings.py 에 STATICFILES_DIRS 항목을 아래와 같이 추가해 준다.

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

 

장고 admin 계정생성
python manage.py createsuperuser

 

 

 

https://docs.djangoproject.com/en/2.1/intro/tutorial01/

 

Writing your first Django app, part 1 | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com

 

https://docs.djangoproject.com/en/2.1/

 

Django documentation | Django documentation | Django

Django The web framework for perfectionists with deadlines. Overview Download Documentation News Community Code Issues About ♥ Donate

docs.djangoproject.com


 

 

 

https://www.inflearn.com/course/django-web-programming/lecture/11579

 

 

Django로 배워보는 Web Programming - 인프런

컴퓨터와 프로그래밍, 그리고 네트워크에 대한 기본적인 패러다임을 가지고. 실질적으로 웹 서비스를 개발할 수 있는 프레임워크인 장고(Django)를 통해서 실질적으로 인터넷상에서 웹 서비스를 배포하는 것을 목표로 합니다! 초급 중급 웹 개발 프레임워크 및 라이브러리 Python Django 온라인 강의 Django

www.inflearn.com

반응형
Comments