이 글은 점프 투 장고를 참고하여 작성하였습니다.
작성자 : 박현빈
개발환경은 Python, PyCharm입니다.
3 - 07) 모델 변경
게시판의 질문, 답변에는 누가 글을 작성했는지 알려주는 "글쓴이" 항목이 필요
Question과 Answer 모델에 "글쓴이"에 해당되는 author 속성을 추가해 보자
모델을 변경한 후에는 makemigrations와 migrate를 통해 데이터베이스를 변경해 주어야 함
(mysite) c:\projects\mysite>python manage.py makemigrations
You are trying to add a non-nullable field 'author' to question without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
Question 모델에 author를 추가하면 이미 등록되어 있던 게시물에 author에 해당되는 값이 저장되어야 하는데, 장고는 author에 어떤 값이 들어가야하는지 알 수 없으므로 지정해주어야 함
Select an option: 1
Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt
>>>
1은 계정의 아이디 값을 의미, author에 admin 계정 등록
(mysite) c:\projects\mysite>python manage.py migrate
migrate를 통해 변경된 내용을 저장
같은 형태로 Answer 모델도 적용해주면 됨
3 - 08) 글쓴이 표시
추가해준 author 속성을 보이도록 표시
템플릿에 코드 추가하여 html을 불러와서 글쓴이를 보여줌
3 - 10) views 파일 분리
뷰파일에 함수가 많아지면 관리가 어려운 문제가 있음
- views 디렉터리의 init.py 파일을 제거
- urls.py의 파일 수정
- views.index 대신 base_views.index 와 같이 전체 경로를 써주기
pybo의 urls.py 수정
from django.urls import path
from .views import base_views, question_views, answer_views
app_name = 'pybo'
urlpatterns = [
# base_views.py
path('',
base_views.index, name='index'),
path('<int:question_id>/',
base_views.detail, name='detail'),
# question_views.py
path('question/create/',
question_views.question_create, name='question_create'),
path('question/modify/<int:question_id>/',
question_views.question_modify, name='question_modify'),
path('question/delete/<int:question_id>/',
question_views.question_delete, name='question_delete'),
# answer_views.py
path('answer/create/<int:question_id>/',
answer_views.answer_create, name='answer_create'),
path('answer/modify/<int:answer_id>/',
answer_views.answer_modify, name='answer_modify'),
path('answer/delete/<int:answer_id>/',
answer_views.answer_delete, name='answer_delete'),
]
URL 매핑시 모듈명이 있기 때문에 누가 보더라도 어떤 뷰 파일의 함수인지 명확하게 인지 가능
config의 urls.py 수정
from django.contrib import admin
from django.urls import include, path
from pybo.views import base_views
urlpatterns = [
path('pybo/', include('pybo.urls')),
path('common/', include('common.urls')),
path('admin/', admin.site.urls),
path('', base_views.index, name='index'), # '/' 에 해당되는 path
]
'GDSC HUFS 3기 > Backend - Django' 카테고리의 다른 글
[Django] 5주차 - 추가 기능 (0) | 2022.06.06 |
---|---|
[Django] 3주차_2_ 파이보 서비스 개발4 (0) | 2022.05.29 |
[Django] 2주차_3_파이보 서비스 개발2 (0) | 2022.05.15 |
[Django] 2주차_2_파이보 서비스 개발1 (0) | 2022.05.15 |
[Django] 2주차_1_장고 기본 요소 3 (0) | 2022.05.14 |