본문 바로가기
IT

스터디노트 - 점프 투 장고 (2) - URL, 뷰, 모델

by 이세진 2021. 1. 31.

이제 장고 설치를 하였으니, <점프 투 장고>와 함께 장고의 기본 요소들을 하나씩 살펴보자.

 

 

주소와 화면을 연결하는 URL과 뷰

앱 생성하기 확인하기

# pybo 앱 생성하기
django-admin startapp pybo

# 개발 서버 구동하기
python3 manage.py runserver

위와 같이 앱 생성 후 구동을 하고, localhost:8000/pybo를 접속해본다.

404 에러가 발생할 것이다. (...)

/pybo/ 페이지에 해당하는 URL 매핑을 하지 않았기 때문에 404 Page not found를 뱉는 것이다.

 

config/urls.py 수정하기

from django.contrib import admin
from django.urls import path
from pybo import views ## 추가

urlpatterns = [
    path('admin/', admin.site.urls),
    path('pybo/', views.index), ## 추가
]

 

pybo/views.py 작성하기

from django.shortcuts import render
from django.http import HttpResponse # 추가

# Create your views here.

## 아래 추가
def index(request):
    return HttpResponse("안녕하세요 pybo에 오신것을 환영합니다.")
HttpResponse는 페이지 요청에 대한 응답을 사용하는 장고 클래스

 

이렇게 작성을 완료한 후, localhost:8000/pybo/를 접속해보면 정상적으로 접속 되는 것을 확인할 수 있다.

 

 

점프 투 장고

 

 

URL 분리하기

config/urls.py 수정하기

from django.contrib import admin
from django.urls import path, include # include 추가
from pybo import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('pybo/', include('pybo.urls')), # views.index를 include('pybo.urls')로 수정
]
pybo 앱과 관련된 URL 요청은 config/urls.py 파일이 아닌 pybo/urls.py 파일을 통해 처리

 

pybo/urls.py 수정하기

from django.urls import path

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

 

데이터를 관리하는 모델

migrate 명령으로 필요로 하는 테이블 생성하기

python3 manage.py migrate



Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

 

DB Browser for SQLite로 테이블 살펴보기

SQLite 다운로드 받기: sqlitebrowser.org/dl/

 

Downloads - DB Browser for SQLite

(Please consider sponsoring us on Patreon 😄) Windows Our latest release (3.12.1) for Windows: Windows PortableApp There is a PortableApp available, but it’s still the previous (3.12.0) release version. It should be updated to 3.12.1 over the next few

sqlitebrowser.org

장고에는 ORM 기능이 있다 - 파이썬으로 데이터 작업을 할 수 있게 해주는 기능
ORM (object relational mapping)

 

모델 만들기

pybo/models.py에 질문/답변 모델 작성하기

from django.db import models

# Create your models here.
class Qustion(models.Model):
    subject = models.CharField(max_length=200)
    content = models.TextField()
    create_date = models.DateTimeField()

class Answer(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    content = models.TextField()
    create_date = models.DateTimeField()

docs.djangoproject.com/en/3.0/ref/models/fields/#field-types

 

Model field reference | Django documentation | Django

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

docs.djangoproject.com

 

config/settings.py를 열어 pybo 앱 등록하기

INSTALLED_APPS = [
    'pybo.apps.PyboConfig', #### 추가
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

 

makemigrations로 테이블 작업 파일 생성하기

python3 manage.py makemigrations
Migrations for 'pybo':
  pybo/migrations/0001_initial.py
    - Create model Question
    - Create model Answer


# pybo/migrations/0001_initial.py 자동 생성된 것 확인

 

migrate로 테이블 생성하기

python3 manage.py migrate


Operations to perform:
  Apply all migrations: admin, auth, contenttypes, pybo, sessions
Running migrations:
  Applying pybo.0001_initial... OK

 

데이터 만들고 저장하고 조회하기

# 장고 셸 실행하기
python3 manage.py shell


Python 3.8.2 (default, Sep 24 2020, 19:37:08)
[Clang 12.0.0 (clang-1200.0.32.21)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)



# Question, Answer 모델 임포트
>>> from pybo.models import Question, Answer

# Question 모델로 Question 모델 데이터 만들기
>>> from django.utils import timezone
>>> q = Question(subject='pybo가 무엇인가요?', content='pybo에 대해서 알고 싶습니다.', create_date=timezone.now())
>>> q.save()

# Question 모델 데이터의 id값 확인하기
>>> q.id
1

# Question 모델로 Question 모델 데이터 1개 더 만들기
>>> q = Question(subject='장고 모델 질문입니다.', content='id는 자동으로 생성되나요?', create_date=timezone.now())
>>> q.save()
>>> q.id
2

# Question 모델 데이터 모두 조회하기
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>, <Question: Question object (2)>]>
반응형

댓글