4월9일차 파이썬 웹구축
webpage - > 코드로 열기 - > 터미널 powershell (x) cmd인지 확인하기
가상환경동작
..\test\scripts\activate
서버동작 (webpage)
python manage.py runserver
컨트롤 로컬호스트를 열어서 /page 입력.
ctrl + c 서버 종료
webpage에 폴더가생긴다.
(test) C:\04_pyweb\webpage> django-admin startapp board
python manage.py runserver
config ㄴ>urls
board ㄴ>views.py
board ㄴ>urls.py
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
migtrate 시켜보기
ctrl c로 서버끊어주고
(test) C:\04_pyweb\webpage> python 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
모델로 구현할 항목.
게시판을 만들어보자.(사용자는 우선 논외로)
게시글 -제목, 내용, 작성일시
댓글 - 연결된 게시글,내용, 작성일시
board - models.py
게시글과 에 대한 모델.
import시킨 모델즈로 모델 갖다쓰겠다
charfield는 길이제한
textfield는 길이제한 안둘때.
기존에 있는 모델을 연결시킬때 foreignkey 퀘스천을 연결시키면서 ondelete 로 일괄적으로 지우겠다.
답글에 대한 모델.
만든 모델을 써먹어보자.
setting.py 에 installed apps
'board.apps.BoardConfig', 추가
config \ settings 파일에 작성할내용.
(test) C:\04_pyweb\webpage> python manage.py migrate
Your models in app(s): 'board' have changes that are not yet reflected in a migration, and so won't be applied.
Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them.
오류가뜬다.
board앱에 있는 모델에 변경된 사항이 마이그레이션이 안되있다.
즉 , 마이그레이트가 안되서 마이그레이트를 못한다??
추가된 모델에대해서 마이그레이션을 해주고 make migrations를 해서 db가 인식을 할 수 있게 해줘야한다.
(test) C:\04_pyweb\webpage> python manage.py makemigrations
마이그레이션폴더안에 만들어지는 파일은 직접 편집하면안된다.
다시 마이그레이트를 해보면
(test) C:\04_pyweb\webpage> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, board, contenttypes, sessions
Running migrations:
Applying board.0001_initial... OK
잘된다.
(test) C:\04_pyweb\webpage> python manage.py sqlmigrate board 0001 <=
보드 앱에 0001번
--
-- Create model Question
--
CREATE TABLE "board_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "subject-- Create model Answer
--
CREATE TABLE "board_answer" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "content" text NOT NULL, "create_date" datetime NOT NULL, "question_id" bigint NOT NULL REFERENCES "board_question" ("id") DEFERRABLE INITIALLY DEFERRED);CREATE INDEX "board_answer_question_id_de1ea245" ON "board_answer" ("question_id"); COMMIT;
원래 sql구문을 일일이 입력을 다해야한다.
근데 그럴필요없이 작업을 다된다.
\
모델 사용해보기. 장고shell을 사용해서 모델을 간단하게 건드려보기.
(test) C:\04_pyweb\webpage> python manage.py shell <=
Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
장고 쉘을 사용할 수 있게 만들어줬다.
그래서 이걸로 뭘하냐?? 원래는 database에 만들어진 모델에다가 데이터를 저장해줘야한다.
일단 장고쉘을 잠깐 이용해서 저장을 하려고 한다 .
>>> from board.models import Question, Answer
아까 만든 모델을 갖다쓰겠다.
>>> from django.utils import timezone
django라는 유틸중에 타임존이라는 유틸이있다 그것을 쓰기위해import시켜준다.
>>> q = Question(subject='첫 번째 게시글', content='어려운 웹서버', create_date=timezone.now())
q라는 변수에다가 question클래스에 맞춰서 데이터를 넣어놓은것.
>>> q.save()
save함수를 통해서 db에저장되었다.
>>> q.id
1
>>> q.subject
'첫 번째 게시글'
db에 저장된 데이터들을 순서대로 자동으로 관리하기위해서 id가 자동으로 붙었다.
(test) C:\04_pyweb\webpage>
(test) C:\04_pyweb\webpage> python manage.py shell
Python 3.11.1 (tags/v3.11.1:a7a450f, Dec 6 2022, 19:58:39) [MSC v.1934 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from board.models import Question, Answer
>>> from django.utils import timezone
>>>
>>> q = Question.objects.get(id=2)
>>> q
<Question: 하나더>
>>> q.subject = 'one more'
>>> q.save()
>>>
>>> Question.objects.get(id=2)
<Question: one more>
>>> q = Question.objects.get(id=1)
>>> q.delete()
(1, {'board.Question': 1})
>>>
>>> Question.objects.all()
<QuerySet [<Question: one more>]>
>>> q= Question.objects.get(id=2)
>>> q
<Question: one more>
>>>
>>> a= Answer(question = q, content='첫번째 댓글입니다', create_date=timezone.now())
>>> a.save()
>>>
<Answer: Answer object (1)>
>>> a.id
1
>>> Answer.objects.get(id=1)
<Answer: Answer object (1)>
>>>
댓글도 자동으로 id가 1부터 매겨진다.
>>> a.question
<Question: one more>
>>>
연결된 게시글이뭐야.
이댓글이 어떤 게시글에 달려있는지를 알려준다.
>>> q
<Question: one more>
>>> q.answer_set.all()
<QuerySet [<Answer: Answer object (1)>]>
>>>
연결된 댓글들 한번에 다가능하다.
question에서 answer셋으로 타고올 수 있다.
눈에 확실하게 안보인다.
그래서 django admin에서 확실하게 관리할 수 있다.
#필수로 알고 있어야 하는 것들.
가상화 환경생성 전체정리
(cmd- 가상화 폴더 저장할 폴더에 위치한 상태 )
python -m venv 이름 (사용자지정 ex : test)
가상화 환경 활성화
(cmd - 가상화 폴더 내부 scripts 폴더에 위치한 상태)
activate
#가상화 환경에 접근하면 프롬프트 앞에 (이름)이 붙어나온다.
(test) 경로
# 비활성화는 같은위치에서 deactivate
가상화 환경에 장고설치
(cmd-가상화환경)
pip install django
장고 프로젝트 생성
cmd- 가상화 환경 - 프로젝트 폴더를 생성할 폴더에 위치한 상태
django-admin startproject config .
장고 프로젝트 내부 앱 생성
(cmd - 가상화 환경 - 프로젝트 폴더에 위치한 상태)
django-admin startapp 앱이름
장고 서버 동작
(cmd - 가상화 환경 - 프로젝트 폴더에 위치한 상태)
python manage.py runserver
다음주는 관리자페이지.
'vscode를 이용한 웹구축(html)' 카테고리의 다른 글
python웹구축 게시글 작성 폼 구현 (0) | 2023.04.16 |
---|---|
파이썬 게시글 목록과 댓글 css(bootstrap) html (0) | 2023.04.16 |
댓글 기능 구현하기 . (0) | 2023.04.15 |
Python 장고관리자계정만들기, 게시글 목록 (0) | 2023.04.15 |
기본 html태그들 4월 9일 강의. (0) | 2023.04.09 |