Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

main

[Django] 프로젝트 내부에 App 만들기 본문

Python

[Django] 프로젝트 내부에 App 만들기

1984 2023. 4. 28. 02:29

App 생성, View 생성

1. 프로젝트 최상단 폴더에 manage.py 파일이 있는 위치에서 아래 명령어를 실행한다.

python manage.py startapp <App_NAME>

2. myApp/views.py 에 간단한 view 코드 작성했다.

3. myApp 폴더 안에 "urls.py" 파일 생성

4. urls.py 에 view를 호출하기 위한 url을 설정한다.

5. 최상위 URLconf(프로젝트 메인 폴더의 urls.py)에서 myApp.urls를 설정한다.

mysite/urls.py

* django.urls.include를 import 해준다.

* include()를 이용해서 myApp.urls를 추가해준다.(admin.site.urls 만 예외)

6. 서버 실행을 위해 아래 명령어를 입력한다.

py manage.py runserver

7. localhost:8000/myApp/으로 접속하면, views.py에서 설정한 index화면이 뜬다.

 

데이터 베이스 생성

데이터 베이스로는 python에 내장된 sqlite3를 사용한다.

mysite/settings.py > DATABASES 항목

1. DB Browser for SQLite 설치

SQLite 데이터베이스 GUI툴

https://sqlitebrowser.org/dl/

 

Downloads - DB Browser for SQLite

(Please consider sponsoring us on Patreon 😄) Windows Our latest release (3.12.2) for Windows: Windows PortableApp Note - If for any reason the standard Windows release does not work (e.g. gives an error), try a nightly build (below). Nightly builds ofte

sqlitebrowser.org

2. mysite/settings.py 파일의 TIMEZONE을 수정한다.

TIME_ZONE = 'Asia/Seoul'

3. 아래 명령어를 사용하여, 데이터베이스에서 테이블을 생성한다.

Django에서 모델의 변경 사항을 데이터베이스에 적용하는 명령어

python manage.py migrate

4. DB Browser for SQLite실행 > 파일 > 읽기 전용으로 데이터베이스 열기...

5. Django 프로젝트 > "db.sqlite3" 파일 선택 > 열기

6. 생성된 테이블을 확인 할 수 있다.

 

모델 생성

1. myApp/models.py 에 모델 생성을 위한 코드를 추가한다.

from django.db import models

class Question(models.Model):
    question_txt = 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)

Question 모델

  • question_txt: CharField 타입, 최대 길이가 200인 문자열 필드.
  • pub_date: DateTimeField 타입, 날짜와 시간을 저장할 수 있는 필드.

Choice 모델

  • question: Question 모델과 ForeignKey로 연결되어 있는 필드.
  • choice_text: CharField 타입, 최대 길이가 200인 문자열 필드.
  • votes: IntegerField 타입, 기본값 0을 가지고 있는 필드.

2. "myApp"이 설치된 것을 프로젝트에 알리기 위해 mysite/settings.py 파일을 수정한다.

INSTALLED_APPS 부분에 "myApp"을 추가한다.

3. myApp 앱에 대한 마이그레이션 파일을 생성하는 명령어를 실행한다.

python manage.py makemigrations <App_NAME>

 

4. 데이터베이스에 변경사항을 적용하는 명령어를 실행한다.

python manage.py migrate

5. myApp_choice, myApp_question 테이블이 생성되었다.

Comments