프로젝트 디렉토리 만들기
$ mkdir [프로젝트디렉토리]
$ cd [프로젝트디렉토리]
파이썬 버전 확인
$ python -V
$ python3 -V
가상환경 만들기 (venv)
$ python3 -m venv [가상환경이름]
가상환경 실행
$ source [가상환경이름]/bin/activate
가상환경 나오기
(가상환경이름) [프로젝트디렉토리]$ deactivate
pip 설치가 안되어있으면 설치
(가상환경이름) [프로젝트디렉토리]$ yum install python-pip
pip 업그레이드
(가상환경이름) [프로젝트디렉토리]$ pip install --upgrade pip
프록시 환경이라면
(가상환경이름) [프로젝트디렉토리]$ pip install --proxy http://xxx.xxx.xxx.xxx:port --upgrade pip
--------------------------------
* 기존 가상환경 설정 파일이 있을경우
(가상환경이름) [프로젝트디렉토리]$ pip install --requirement [파일명].txt
또는
(가상환경이름) [프로젝트디렉토리]$ pip install -r [파일명].txt
프록시 환경이라면
(가상환경이름) [프로젝트디렉토리]$ pip install --proxy http://xxx.xxx.xxx.xxx:port -r [파일명].txt
* 가상환경 설정파일 만들기
(가상환경이름) [프로젝트 디렉토리]# pip freeze > [파일명].txt
--------------------------------
가상환경에 설치된 python 모듈 경로
(가상환경이름)/lib/python3.6/site-packages/
django 버전 확인
(가상환경이름) [프로젝트디렉토리]$ python3 -m django --version
django 업그레이드
# pip install -U django
프록시 환경 일 경우
# pip install -U --proxy http://xxx.xxx.xxx.xxx:port django
django 삭제
# pip uninstall django
django 설치하기 (특정 버전 설치 => pip install django~=2.0.0)
(가상환경이름) [프로젝트디렉토리] $ pip install django
프록시 환경 일 경우
(가상환경이름) [프로젝트디렉토리]$ pip install --proxy http://xxx.xxx.xxx.xxx:port django
* 현재일 기준 django 최신 버전은 2.2.X 인데 sqlite3 버전오류등 조금 애매한 부분이 있어서 난 2.0.0설치함
그러나 mysql로 연결하면 정상적으로 실행됨(2.2.4)
2.0설치후 django 업그레드 하면 괜찮음
Django 프로젝트 생성
(가상환경이름) [프로젝트디렉토리]$ django-admin startproject [프로젝트명] .
점 (.)은 현재 디렉토리에 장고를 설치 (.안쓰면 [프로젝트명]/[프로젝트명]안에 설정파일들이 생성
[프로젝트디렉토리]/
[가상환경디렉토리]
manage.py
[프로젝트명]/
__init__.py
settings.py
urls.py
wsgi.py
난, 점 (.)을 안쓰고 설치
[프로젝트디렉토리]/
[가상환경디렉토리]
[프로젝트명]/
manage.py
[프로젝트명]/
__init__.py
settings.py
urls.py
wsgi.py
프로젝트 삭제
프로젝트 폴더와 manage.py 파일 삭제
사이트 실행 (Port를 생략하면 기본적으로 8000 Port사용)
(가상환경이름)[프로젝트디렉토리]$ python3 manage.py runserver [포트]
이때 2.2.X버전의 경우 SQlite오류 발생할 수 있음. 2.0.0에서 실행 후 업그레이드 하면 괜찮음.
mysql 연결하면 괜찮음
(원인을 아시는분 알려주세요^^;)
실행중인 Django 프로세스 확인
$ ps -ef | grep runserver | grep -v grep
서버중지
$ kill -9 [프로세스 아이디]
runserver는 테스트 용으로 사용하며, 서비스 시에는 apache등 사용
==========================================================
git 연결
gitlab에 프로젝트 만들고
해당 프로젝트에 git 셋팅
https://devlink.tistory.com/215
기존 DB 스키마가 있는경우 (DB를 다시 만드는 경우)
신규 DB를 만들고, settings.py에서 DB정보를 일치 시켜주고,
해당 APP의 migrations 디렉토리 안에 있는 파일 삭제 (__init__.py 파일은 삭제하지 않음)
스키마 생성
python3 manage.py makemigrations
마이그레이션 진행
python3 manage.py migrate
https://devlink.tistory.com/301?category=721886
==========================================================
아파치 연동
참고
https://tutorial.djangogirls.org/ko/django_installation/
https://docs.djangoproject.com/ko/2.2/intro/tutorial03/
========================================
mod_wsgi 설치
* 설치된 python 버전과 호환되는 mod_wsgi를 설치해야 함.
버전이 안맞으면 특별한 오류 없이 연동이 되지 않음.
python 버전 확인
# python -V
python3.6.8 기준
python36u-mod_wsgi 설치
yum으로 설치
# yum install python36u-mod_wsgi
rpm으로 설치
https://centos.pkgs.org/7/ius-archive-x86_64/python36u-mod_wsgi-4.5.14-2.ius.centos7.x86_64.rpm.html
다운로드
# rpm -ivh python36u-mod_wsgi-4.5.14-2.ius.centos7.x86_64.rpm
설치 확인
# rpm -qa mod_wsgi
apache 설정
vi /etc/httpd/conf/httpd.conf 에 추가
Listen 8000
#가상환경 사용시 venv 경로
WSGIPythonHome [프로젝트 디렉토리경로]/[프로젝트명]/myvenv
<VirtualHost *:8000>
ServerName www.example.com
WSGIScriptAlias / [프로젝트 디렉토리경로]/[프로젝트명]/wsgi.py (wsgi.py가 위치한 경로)
DocumentRoot [프로젝트 디렉토리경로]
<Directory [프로젝트 디렉토리경로]/[프로젝트명]>
<Files wsgi.py>
Order deny,allow
Allow from all
Require all granted
</Files>
</Directory>
# 이미지등 정적 파일 경로
Alias /static/ /var/www/balance/www/static/
<Directory /var/www/balance/www/static>
Allow from all
</Directory>
</VirtualHost>
wsgi.py 파일 수정
"""
WSGI config for mysite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os, sys
from django.core.wsgi import get_wsgi_application
path = os.path.abspath(__file__+'/../..')
if path not in sys.path:
sys.path.append(path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '[프로젝트명].settings')
application = get_wsgi_application()
아파치 재시작
# systemctl restart httpd
참고
https://lohanyeon.github.io/2018/django-apache/
https://yongbeomkim.github.io/django/mdc-wsgi-server/
http://blog.naver.com/PostView.nhn?blogId=gghso&logNo=221457781320
========================================
새로운 APP 만들기
(가상환경이름) [프로젝트디렉토리]# python3 manage.py startapp [APP명]
[APP명]의 디렉토리 생성
[프로젝트 디렉토리]/
manage.py
[프로젝트명]/
__init__.py
settings.py
urls.py
wsgi.py
[APP명]/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
[프로젝트명]/settings.py 에 [APP명] 추가, STATIC_ROOT추가 및 설정 변경
LANGUAGE_CODE = 'ko'
TIME_ZONE = 'Asia/Seoul'
.
.
.
ALLOWED_HOSTS = ['localhost', '.도메인']
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'[APP명]',
]
.
.
.
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
django의 기본적인 static 파일(js, css등) 파일 이동하기
(가상환경이름) [프로젝트디렉토리]# python3 manage.py collectstatic
오류 발생시
CommandError: Collecting static files cancelled.
(가상환경이름) [프로젝트디렉토리]# python3 manage.py collectstatic --noinput
[새로만든 APP]으로 URL연결 하기
[프로젝트디렉토리]/[프로젝트명]/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('[새로만든 APP].urls')),
]
[프로젝트디렉토리]/[APP명]/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'), 추가
]
뷰 작성
[프로젝트디렉토리]/[APP명]/views.py
from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Post
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.
def post_list(request):
posts = Post.objects.all().order_by('published_date')
page = request.GET.get('page', 1)
paginator = Paginator(posts, 2)
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
return render(request, '[APP명]/post_list.html', {'posts': posts})
모델작성 (model == database table)
[프로젝트 디렉토리]/[APP명]/models.py
from django.db import models
from django.utils import timezone
# 클래스 이름의 첫 글자는 대문자
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
작성한 model을 기준으로 Migration 파일 생성
(가상환경이름) [프로젝트 디렉토리]# python3 manage.py makemigrations [APP명] (APP명 생략시 전체 적용)
디비에 스키마를 반영
(가상환경이름) [프로젝트 디렉토리]# python3 manage.py migrate
템플릿 만들기
[프로젝트 디렉토리]/templates 생성 (templates 디렉토리 생성 위치는 개인적 취향)
[프로젝트 디렉토리]/templates/[APP명]/post_list.html 파일 편집
root 개념이므로
[프로젝트 디렉토리]/[프로젝트명]/settings.py 경로 수정
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], #templates 디렉토리를 root에 만들경우 지정
'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',
],
},
},
]
기본적으로 해당 [APP]안에 templates디렉토리가 위치하면 settings.py 경로 수정이 필요 없음
[프로젝트 디렉토리]/
manage.py
[프로젝트명]/
__init__.py
settings.py
urls.py
wsgi.py
[APP명]/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
templates/
[APP명]
템플릿파일.html
=================================
관리자 url (실제로 사용하기는 어렵고..)
http://localhost:8000/admin/
슈퍼사용자 등록
(가상환경이름) [프로젝트 디렉토리]# python3 manage.py createsuperuser
이름, 이메일, 패스워드 입력
* 개발서버 구동시 CSS가 적용되지만, 아파치와 연동하면 CSS가 적용되지 않음
STATIC_ROOT = os.path.join(BASE_DIR, 'static') 를 통해 정적 파일을 저장하고,
아파치설정에 Alias 적용
참고
http://blog.naver.com/PostView.nhn?blogId=gghso&logNo=221457781320
만일 관리자 페이지에서 테이블이 없다는 등의 오류가 발생하면
# python3 manage.py migrate
==================================
static 디렉토리
정적 파일 (이미지, css, js 등) 을 보관하는 디렉토리
생성 후 apache설정에 Alias 적용 해야함
Listen 8000
#가상환경 사용시 venv 경로
WSGIPythonHome [프로젝트 디렉토리경로]/[프로젝트명]/myvenv
<VirtualHost *:8000>
ServerName www.example.com
WSGIScriptAlias / [프로젝트 디렉토리경로]/[프로젝트명]/wsgi.py (wsgi.py가 위치한 경로)
DocumentRoot [프로젝트 디렉토리경로]
<Directory [프로젝트 디렉토리경로]/[프로젝트명]>
<Files wsgi.py>
Order deny,allow
Allow from all
Require all granted
</Files>
</Directory>
# 이미지등 정적 파일 경로
Alias /static/ /var/www/balance/www/static/
<Directory /var/www/balance/www/static>
Allow from all
</Directory>
</VirtualHost>
참조 : http://pythonstudy.xyz/python/article/314-Static-%ED%8C%8C%EC%9D%BC
==================================
templates 디렉토리
각 App 폴더 밑에 templates 서브폴더를 만들고 그 안에 App명을 사용하여 템플릿 파일을 정리할수 도있고,
관리의 필요성에 따라 root에 만들수도 있다. root에 만들경우는 경로를 명시해야 한다.
'DIRS': [os.path.join(BASE_DIR, 'templates')] 추가
root에 만들더라도 템플릿 네임스페이싱은 유지해야 함 (/templates/App명/템플릿파일.html)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')], #templates 디렉토리를 root에 만들경우 지정
'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',
],
},
},
]
templates등 적용할때 반영이 안되는 경우가 있는데 이때는 아파치를 재시작 해야 한다.
참고할만한 튜토리얼
https://tutorial.djangogirls.org/ko/django_templates/
http://pythonstudy.xyz/python/article/314-Static-%ED%8C%8C%EC%9D%BC (디렉토리구조 참조)
https://docs.djangoproject.com/ko/2.2/intro/tutorial03/
==================================
MySQL 연결
mysqlclient 설치
(가상환경이름) [프로젝트 디렉토리] $ pip install mysqlclient
(가상환경이름) [프로젝트 디렉토리] $ pip install --proxy http://xxx.xxx.xxx.xxx:포트 mysqlclient
[프로젝트 디렉토리]/[프로젝트명]/settings.py 에 DATABASES 연결 문자열 수정
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DB 이름',
'USER': '계정',
'PASSWORD': '패스워드',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"'
}
}
}
다시
작성한 model을 기준으로 Migration 파일 생성
(가상환경이름) [프로젝트 디렉토리]# python3 manage.py makemigrations [APP명] (APP명 생략시 전체 적용)
디비에 스키마를 반영
(가상환경이름) [프로젝트 디렉토리]# python3 manage.py migrate
조금 황당하지만 mysql 연결 후 500 (internal server error)에러 발생..
가상환경에 mysqlclient 설치했지만...
어쨌는 로컬에 mysqlclient 설치하니까 됨..
만일 pycharm에서 DB Navigater사용시 테이블에 데이터 안보이면
commit 해주거나, Settings > Properties > Auto-Commit 체크
추가한 테이블을 django 관리 사이트에서 관리를 하려면,
admin.py 에 추가
from django.contrib import admin
from .models import 데이터 Class명
# Register your models here.
admin.site.register(데이터 Class명)
==================================
네임스페이스 사용
APP을 여러개 만들어 사용할경우 네임스페이스 사용 가능
각각의 APP의 urls.py에
app_name = 'APP 네임스페이스'
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new', views.post_new, name='post_new'),
]
[APP 네임스페이스]:post_list 형식으로 사용
template에서도..
<a href="{% url '[APP 네임스페이스]:post_list' %}" >링크</a>
'Python' 카테고리의 다른 글
pycharm 가상환경 경로 설정 (0) | 2019.11.29 |
---|---|
django 현재 url 가져오기 (0) | 2019.11.26 |
django 이메일 보내기 (smtplib) (0) | 2019.11.14 |
dgango template 에서 숫자에 콤마 찍기 (0) | 2019.10.29 |
python 정규식 (0) | 2019.10.29 |