1. Django 설치하기
$ sudo apt-get install python-django
$ django-admin.py --version
2. Django 프로젝트 만들기
$ django-admin.py startproject django_example
3. Database 연동
$ vi django_example/settings.py
12 DATABASES = {
13 'default': {
14 'ENGINE': ''django.db.backends.sqlite3',
15 'NAME': 'exampledb',
16 'USER': '',
18 'PASSWORD': '',
19 'HOST': '',
20 'PORT': '',
21 }
22 }
$ python manage.py syncdb
4. 서버 실행
- 서버는 기본으로 8000 번 포트로 실행되므로 포트를 생략할 수 있다.
$ python manage.py runserver <8000>
5. 프로젝트 만들기
$ python manage.py startapp example
6. view 작성
$ vi example/views.py
1 # -*- coding: utf-8 -*- (다국어 표현을 위한 주석)
2
3 # Create your views here.
4 from django.http import HttpResponse
5
6 def main_page(request):
7 output = '''
8 <html>
9 <head><title>%s</title></head>
10 <body>
11 <h1>%s</h1>
12 </body>
13 </html>
14 ''' % (
15 'Django Example',
16 'Hello World !!'
17 )
18 return HttpResponse(output)
7. URL 과 view 매핑
$ vi django_example/urls.py
1 from django.conf.urls import patterns, include, url
2 from example.views import *
3
4 urlpatterns = patterns('',
6 (r'^$', main_page),
7 )
8. Model 만들기
- Model 에서 사용하는 Field type
IntegerField
TextField
CharField
DateTimeField
EmailField
URLField
FileField
- Department 모델 만들기
$ vi example/models.py
1 from django.contrib.auth.models import User
2 from django.db import models
3
4 class Department(models.Model):
5 department_name = models.TextField()
6 user = models.ForeignKey(User)
- settings 파일에 INSTALLED_APPS 에 APP 을 등록하여 model 활성화
$ vi django_example/settings.py
116 INSTALLED_APPS = (
117 'django.contrib.auth',
118 'django.contrib.contenttypes',
119 'django.contrib.sessions',
120 'django.contrib.sites',
121 'django.contrib.messages',
122 'django.contrib.staticfiles',
123 'example',
128 )
- Model DB 테이블 생성
$ python manage.py syncdb
- DDL 문 SQL 확인
$ python manage.py sql example
- Data 저장 및 확인
$ python manage.py shell
>>> from example.models import *
>>> from django.contrib.auth.models import User
>>> User.objects.all()
>>> user = User.objects.get(id=1)
>>> print user
>>> dir(user)
>>> department1 = Department(department_name='Cloud Team', user=user)
>>> department1.save()
9. Template 만들기
- template 디렉토리 지정하기
$ mkdir -p templates
$ vi django_example/settings.py
3 import os.path
...
112 TEMPLATE_DIRS = (
113 os.path.join(os.path.dirname(__file__), '../templates'),
114 )
- template 파일 만들기
$ vi templates/main_page.html
1 <html>
2 <head><title>{{ title }}</title></head>
3 <body>
4 <h1>{{ greeting }}</h1>
5 </body>
6 </html>
- view 파일 수정
$ vi example/views.py
1 # -*- coding: utf-8 -*-
2
3 from django.http import HttpResponse
4 from django.template import Context
5 from django.template.loader import get_template
6
7 def main_page(request):
8 template = get_template('main_page.html')
9 variables = Context({
10 'title': 'My Example',
11 'greeting': 'Hello Stephen !!',
12 })
13 output = template.render(variables)
14 return HttpResponse(output)
10. 복잡한 화면 만들기
- url 을 user/username 형식으로 매핑 (username 은 stack 이라는 user 명을 사용)
$ vi django_example/urls.py
8 urlpatterns = patterns('',
9 (r'^$', main_page),
10 (r'^user/(\w+)/$', user_page),
11 )
- view 를 수정
$ vi example/views.py
3 from django.contrib.auth.models import User
4 from django.http import Http404
18 def user_page(request, username):
19 try:
20 user = User.objects.get(username=username)
21 except:
22 raise Http404('Cant not found user')
23
24 dept = user.department_set.all()
25
26 template = get_template('user_page.html')
27 variables = Context({
28 'username': username,
29 'department': dept,
30 })
31 output = template.render(variables)
32 return HttpResponse(output)
- page 생성
$ vi templates/user_page.html
1 <html>
2 <head><title>User: {{ username }}</title></head>
3 <body>
4 <h1>{{ username }}'s Department</h1>
5 {% if department %}
6 <ul>
7 {% for dept in department %}
8 <li>{{ dept.department_name }}</li>
9 {% endfor %}
10 </ul>
11 {% else %}
12 <p>There's is no department</p>
13 {% endif %}
14 </body>
15 </html>