102
건건건건 건건건 건건 건건건

건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Embed Size (px)

Citation preview

Page 1: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

건전지로 달리는쟝고 세미나

Page 2: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

파트 2

Page 3: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Last time

Page 4: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

MVC

Page 5: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Views and URLconfs

Page 6: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# views.pyfrom django.shortcuts import render_to_responseimport datetime

def current(request): now = datetime.datetime.now() return render_to_response('current.html', {'current_date': now})

# views.pyfrom django.shortcuts import render_to_responseimport datetime

def current(request): now = datetime.datetime.now() return render_to_response('current.html', {'current_date': now})

Page 7: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# urls.pyfrom django.conf.urls.defaults import *from views import hello, current

urlpatterns = patterns('', ('^hello/$', hello), ('^current/$', current),)

# urls.pyfrom django.conf.urls.defaults import *from views import hello, current

urlpatterns = patterns('', ('^hello/$', hello), ('^current/$', current),)

Page 8: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Templates

Page 9: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

{% extends "base_generic.html" %}{% block title %}{{ section.title }}{% endblock %}{% block content %}<h1>{{ section.title }}</h1>{% for story in story_list %}<h2> <a href="{{ story.get_absolute_url }}"> {{ story.headline|upper }} </a></h2><p>{{ story.tease|truncatewords:"100" }}</p>{% endfor %}{% endblock %}

{% extends "base_generic.html" %}{% block title %}{{ section.title }}{% endblock %}{% block content %}<h1>{{ section.title }}</h1>{% for story in story_list %}<h2> <a href="{{ story.get_absolute_url }}"> {{ story.headline|upper }} </a></h2><p>{{ story.tease|truncatewords:"100" }}</p>{% endfor %}{% endblock %}

Page 10: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Today

Page 11: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Models

Page 12: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Database

Page 13: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

SELECT * FROM Professors order by id

SELECT * FROM Professors order by id

Page 14: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

MTV

Page 15: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

from django.shortcuts import render_to_responseimport MySQLdbdef course_list(request): db = MySQLdb.connect(user='hodduc', db= 'sparcsdb', passwd='mandu', host='localhost') cursor = db.cursor() cursor.execute('SELECT code FROM courses ORDER BY code') codes = [row[0] for row in cursor.fetchall()] db.close() return render_to_response( 'course_list.html', {‘codes': codes})

from django.shortcuts import render_to_responseimport MySQLdbdef course_list(request): db = MySQLdb.connect(user='hodduc', db= 'sparcsdb', passwd='mandu', host='localhost') cursor = db.cursor() cursor.execute('SELECT code FROM courses ORDER BY code') codes = [row[0] for row in cursor.fetchall()] db.close() return render_to_response( 'course_list.html', {‘codes': codes})

Page 16: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

from django.shortcuts import render_to_responsefrom courses.models import Book

def course_list(request): courses = Course.objects.order_by('code') return render_to_response( 'course_list.html', {'codes': codes})

from django.shortcuts import render_to_responsefrom courses.models import Book

def course_list(request): courses = Course.objects.order_by('code') return render_to_response( 'course_list.html', {'codes': codes})

Page 17: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Object-relational mapping

Page 18: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# settings.py DATABASES = { 'mysql': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user_data', 'USER': 'mysql_user', 'PASSWORD': 'priv4te', }}

# settings.py DATABASES = { 'mysql': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user_data', 'USER': 'mysql_user', 'PASSWORD': 'priv4te', }}

Page 19: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase' } }

# settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase' } }

Page 20: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py shell

… >>> from django.db import connection >>> cursor = connection.cursor()

$ python manage.py shell

… >>> from django.db import connection >>> cursor = connection.cursor()

Page 21: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# settings.pyDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase' }, 'mysql': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user_data', 'USER': 'mysql_user', 'PASSWORD': 'priv4te', }}

# settings.pyDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'mydatabase' }, 'mysql': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'user_data', 'USER': 'mysql_user', 'PASSWORD': 'priv4te', }}

Page 22: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py startapp courses $ python manage.py startapp courses

Page 23: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

courses/ __init__.pymodels.pytests.pyviews.py

courses/ __init__.pymodels.pytests.pyviews.py

Page 24: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# courses/models.pyfrom django.db import models

class Professor(models.Model): name = models.CharField(max_length=10) email = models.EmailField() website = models.URLField() job_date = models.DateField()

class Course(models.Model): code = models.CharField(max_length=30) department = models.CharField(max_length=20) semester = models.IntegerField() year = models.IntegerField()

# courses/models.pyfrom django.db import models

class Professor(models.Model): name = models.CharField(max_length=10) email = models.EmailField() website = models.URLField() job_date = models.DateField()

class Course(models.Model): code = models.CharField(max_length=30) department = models.CharField(max_length=20) semester = models.IntegerField() year = models.IntegerField()

Page 25: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# courses/models.pyfrom django.db import models

class Professor(models.Model): name = models.CharField(max_length=10) email = models.EmailField() website = models.URLField() job_date = models.DateField()

class Course(models.Model): code = models.CharField(max_length=30) department = models.CharField(max_length=20) semester = models.IntegerField() year = models.IntegerField() professor = models.ForeignKey(Professor)

# courses/models.pyfrom django.db import models

class Professor(models.Model): name = models.CharField(max_length=10) email = models.EmailField() website = models.URLField() job_date = models.DateField()

class Course(models.Model): code = models.CharField(max_length=30) department = models.CharField(max_length=20) semester = models.IntegerField() year = models.IntegerField() professor = models.ForeignKey(Professor)

Page 26: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# courses/models.pyfrom django.db import models

class Professor(models.Model): name = models.CharField(max_length=10) email = models.EmailField() website = models.URLField() job_date = models.DateField()

class Course(models.Model): code = models.CharField(max_length=30) department = models.CharField(max_length=20) semester = models.IntegerField() year = models.IntegerField() professors = models.ManyToManyField(Professor)

# courses/models.pyfrom django.db import models

class Professor(models.Model): name = models.CharField(max_length=10) email = models.EmailField() website = models.URLField() job_date = models.DateField()

class Course(models.Model): code = models.CharField(max_length=30) department = models.CharField(max_length=20) semester = models.IntegerField() year = models.IntegerField() professors = models.ManyToManyField(Professor)

Page 27: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# settings.py

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'courserating.courses',)

# settings.py

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'courserating.courses',)

Page 28: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py validate $ python manage.py validate

Page 29: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py validate 0 errors found $ python manage.py validate 0 errors found

Page 30: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py sqlall courses $ python manage.py sqlall courses

Page 31: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py sqlall courses BEGIN; CREATE TABLE "courses_professor" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(10) NOT NULL, "email" varchar(75) NOT NULL, "website" varchar(200) NOT NULL, "job_date" date NOT NULL ) ;

$ python manage.py sqlall courses BEGIN; CREATE TABLE "courses_professor" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(10) NOT NULL, "email" varchar(75) NOT NULL, "website" varchar(200) NOT NULL, "job_date" date NOT NULL ) ;

Page 32: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

CREATE TABLE "courses_course_professors" ( "id" integer NOT NULL PRIMARY KEY, "course_id" integer NOT NULL, "professor_id" integer NOT NULL REFERENCES "courses_professor" ("id"), UNIQUE ("course_id", "professor_id"));CREATE TABLE "courses_course" ( "id" integer NOT NULL PRIMARY KEY, "code" varchar(30) NOT NULL, "department" varchar(20) NOT NULL, "semester" integer NOT NULL, "year" integer NOT NULL);COMMIT;

CREATE TABLE "courses_course_professors" ( "id" integer NOT NULL PRIMARY KEY, "course_id" integer NOT NULL, "professor_id" integer NOT NULL REFERENCES "courses_professor" ("id"), UNIQUE ("course_id", "professor_id"));CREATE TABLE "courses_course" ( "id" integer NOT NULL PRIMARY KEY, "code" varchar(30) NOT NULL, "department" varchar(20) NOT NULL, "semester" integer NOT NULL, "year" integer NOT NULL);COMMIT;

Page 33: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py syncdb $ python manage.py syncdb

Page 34: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py syncdb Creating table auth_permission … Creating table courses_professor Creating table courses_course_professors Creating table courses_course

You just installed Django's auth system, which means you don't have any superusers defined. Would you like to create one now? (yes/no): no Installing index for auth.Permission model … Installing index for courses.Course_professors model No fixtures found.

$ python manage.py syncdb Creating table auth_permission … Creating table courses_professor Creating table courses_course_professors Creating table courses_course

You just installed Django's auth system, which means you don't have any superusers defined. Would you like to create one now? (yes/no): no Installing index for auth.Permission model … Installing index for courses.Course_professors model No fixtures found.

Page 35: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py shellPython 2.6.4 (r264:75706, Mar 31 2010, 23:32:27)[GCC 4.3.4] on linux2Type "help", "copyright", "credits" or "license" for more information.(InteractiveConsole)>>>

$ python manage.py shellPython 2.6.4 (r264:75706, Mar 31 2010, 23:32:27)[GCC 4.3.4] on linux2Type "help", "copyright", "credits" or "license" for more information.(InteractiveConsole)>>>

Page 36: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> from courses.models import Professor>>> p1 = Professor(name='Kim Doguk', email='[email protected]', website='http://twitter.com/logue311',job_date='2010-06-05')>>> p1.save()>>> p2 = Professor(name='Oh Youngtaek', email='[email protected]', website='http://twitter.com/dongx3',job_date='2010-06-05') >>> p2.save()>>> professor_list = Professor.objects.all()>>> professor_list[<Professor: Professor object>, <Professor: Professor object>]

>>> from courses.models import Professor>>> p1 = Professor(name='Kim Doguk', email='[email protected]', website='http://twitter.com/logue311',job_date='2010-06-05')>>> p1.save()>>> p2 = Professor(name='Oh Youngtaek', email='[email protected]', website='http://twitter.com/dongx3',job_date='2010-06-05') >>> p2.save()>>> professor_list = Professor.objects.all()>>> professor_list[<Professor: Professor object>, <Professor: Professor object>]

Page 37: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> p1.id1>>> p2.id2

>>> p1.id1>>> p2.id2

Page 38: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> p1.email = '[email protected]'>>> p1.save()>>> p2.email = '[email protected]'>>> p2.save()

>>> p1.email = '[email protected]'>>> p1.save()>>> p2.email = '[email protected]'>>> p2.save()

Page 39: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> Professor.objects.all()>>> Professor.objects.filter(job_date="2010-06-05")>>> Professor.objects.filter(... email__contains="@sparcs.org“... )>>> Professor.objects.get(name__contain="Doguk")>>> Professor.objects.order_by("name")>>> Professor.objects.order_by("-job_date")>>> Professor.objects.filter(... email__contains="@sparcs.org“... ).order_by("-job_date")>>> Professor.objects.order_by("name")[0]>>> Professor.objects.order_by("name")[0:2]

>>> Professor.objects.all()>>> Professor.objects.filter(job_date="2010-06-05")>>> Professor.objects.filter(... email__contains="@sparcs.org“... )>>> Professor.objects.get(name__contain="Doguk")>>> Professor.objects.order_by("name")>>> Professor.objects.order_by("-job_date")>>> Professor.objects.filter(... email__contains="@sparcs.org“... ).order_by("-job_date")>>> Professor.objects.order_by("name")[0]>>> Professor.objects.order_by("name")[0:2]

Page 40: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> p = Professor.objects.get(name="Kim Doguk")>>> p.name = "Kim Wheel">>> p.save()

>>> Professor.objects.all().update(job_date="2010-02-23")

>>> p = Professor.objects.get(name__contains="Oh")>>> p.delete()>>> Professor.objects.filter(... name__contains="Park").delete()>>> Professor.objects.all().delete()

>>> p = Professor.objects.get(name="Kim Doguk")>>> p.name = "Kim Wheel">>> p.save()

>>> Professor.objects.all().update(job_date="2010-02-23")

>>> p = Professor.objects.get(name__contains="Oh")>>> p.delete()>>> Professor.objects.filter(... name__contains="Park").delete()>>> Professor.objects.all().delete()

Page 41: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> profs = Professor.objects.all()>>> print profs[<Professor: Kim Doguk>, <Professor: Oh Youngtaek>]>>> print profs.querySELECT "courses_professor"."id", "courses_professor"."name", "courses_professor"."email", "courses_professor"."website", "courses_professor"."job_date" FROM "courses_professor"

>>> profs = Professor.objects.all()>>> print profs[<Professor: Kim Doguk>, <Professor: Oh Youngtaek>]>>> print profs.querySELECT "courses_professor"."id", "courses_professor"."name", "courses_professor"."email", "courses_professor"."website", "courses_professor"."job_date" FROM "courses_professor"

Page 42: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Admin Sites

Page 43: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

django.contrib

Page 44: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# settings.py

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'courserating.courses', 'django.contrib.admin',)

# settings.py

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'courserating.courses', 'django.contrib.admin',)

Page 45: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# urls.py

from django.conf.urls.defaults import *from django.contrib import adminfrom views import *

admin.autodiscover()

urlpatterns = patterns('', ('^hello/$', hello), ('^current/$', current), ('^admin/', include(admin.site.urls)),)

# urls.py

from django.conf.urls.defaults import *from django.contrib import adminfrom views import *

admin.autodiscover()

urlpatterns = patterns('', ('^hello/$', hello), ('^current/$', current), ('^admin/', include(admin.site.urls)),)

Page 46: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# courses/admin.py

from django.contrib import adminfrom courses.models import Professor, Course

admin.site.register(Professor)admin.site.register(Course)

# courses/admin.py

from django.contrib import adminfrom courses.models import Professor, Course

admin.site.register(Professor)admin.site.register(Course)

Page 47: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py runserver $ python manage.py runserver

Page 48: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 49: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 50: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 51: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 52: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 53: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 54: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 55: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Forms

Page 56: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

HttpRequest

Page 57: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

request.path /hello/request.get_host() 127.0.0.1:8000request.get_full_path /hello?a=1request.is_secure() False

Page 58: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

request.META['HTTP_REFERER']request.META['HTTP_USER_AGENT']request.META['REMOTE_ADDR']

Page 59: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

request.GET['query']request.POST['password']

Page 60: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Forms from Scratch

Page 61: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# views.pydef add_professor(request): errors = [] if request.method == 'POST': if not request.POST.get('name' , ''): errors.append('Enter a name.') if not request.POST.get('email', ''): errors.append('Enter a email.') if not request.POST.get('website' , ''): errors.append('Enter a website') if not errors: p = Professor(name=request.POST['name'],email= request.POST['email'],website=request.POST['website'], job_date=datetime.now()) p.save() return HttpResponseRedirect('/hell/') return render_to_response('add_professor.html', { 'errors': errors, 'subjects': request.POST.get('subject', ''), 'message': request.POST.get('message', ''), 'email': request.POST.get('email', ''), })

# views.pydef add_professor(request): errors = [] if request.method == 'POST': if not request.POST.get('name' , ''): errors.append('Enter a name.') if not request.POST.get('email', ''): errors.append('Enter a email.') if not request.POST.get('website' , ''): errors.append('Enter a website') if not errors: p = Professor(name=request.POST['name'],email= request.POST['email'],website=request.POST['website'], job_date=datetime.now()) p.save() return HttpResponseRedirect('/hell/') return render_to_response('add_professor.html', { 'errors': errors, 'subjects': request.POST.get('subject', ''), 'message': request.POST.get('message', ''), 'email': request.POST.get('email', ''), })

Page 62: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# add_professor.html<html><body><h1>Add Professor</h1> {% if errors %} <ul> {% for error in errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %}‘ <form action=‘/add_professor/’ method=‘post’> <p>name : <input type=‘text’ name=‘name’ value=‘{{ subject }}’></p> <p>email : <input type=‘text’ name=‘email’ value=‘{{ subject }}’></p> <p>website : <input type=‘text’ name=‘website’ value=‘{{ subject }}’></p> <p><input type=‘submit’/></p> </form></body></html>

# add_professor.html<html><body><h1>Add Professor</h1> {% if errors %} <ul> {% for error in errors %} <li>{{ error }}</li> {% endfor %} </ul> {% endif %}‘ <form action=‘/add_professor/’ method=‘post’> <p>name : <input type=‘text’ name=‘name’ value=‘{{ subject }}’></p> <p>email : <input type=‘text’ name=‘email’ value=‘{{ subject }}’></p> <p>website : <input type=‘text’ name=‘website’ value=‘{{ subject }}’></p> <p><input type=‘submit’/></p> </form></body></html>

Page 63: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 64: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

django.forms

Page 65: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# forms.pyfrom django import forms

class ProfessorForm(forms.Form): name = forms.CharField() email = forms.CharField() website = forms.CharField(required=False)

# forms.pyfrom django import forms

class ProfessorForm(forms.Form): name = forms.CharField() email = forms.CharField() website = forms.CharField(required=False)

Page 66: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# forms.pyfrom django import forms

class ProfessorForm(forms.Form): name = forms.CharField(max_length=100) email = forms.CharField(widget= forms.Textarea) website = forms.CharField(required=False)

# forms.pyfrom django import forms

class ProfessorForm(forms.Form): name = forms.CharField(max_length=100) email = forms.CharField(widget= forms.Textarea) website = forms.CharField(required=False)

Page 67: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# forms.pyfrom django import forms

class ProfessorForm(forms.Form): name = forms.CharField(max_length=100) email = forms.CharField(widget= forms.Textarea) website = forms.CharField(required=False)

def clean_email(self): email = self.cleaned_data[‘email’] if email.find(‘@’) == -1: raise forms.ValidationError(‘Not valid email!’) return email

# forms.pyfrom django import forms

class ProfessorForm(forms.Form): name = forms.CharField(max_length=100) email = forms.CharField(widget= forms.Textarea) website = forms.CharField(required=False)

def clean_email(self): email = self.cleaned_data[‘email’] if email.find(‘@’) == -1: raise forms.ValidationError(‘Not valid email!’) return email

Page 68: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> form forms import ProfessorForm>>> f = ProfessorForm()>>> form forms import ProfessorForm>>> f = ProfessorForm()

Page 69: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> print f<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="100" /></td></tr><tr><th><label for="id_email">Email:</label></th><td><textarea id="id_email" rows="10" cols="40" name="email"></textarea></td></tr><tr><th><label for="id_website">Website:</label></th><td><input type="text" name="website" id="id_website" /></td></tr>

>>> print f<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="100" /></td></tr><tr><th><label for="id_email">Email:</label></th><td><textarea id="id_email" rows="10" cols="40" name="email"></textarea></td></tr><tr><th><label for="id_website">Website:</label></th><td><input type="text" name="website" id="id_website" /></td></tr>

Page 70: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> print f['name']<input id="id_name" type="text" name="name" maxlength="100" />>>> print f['email']<textarea id="id_email" rows="10" cols="40" name="email"></textarea>>>> print f['website']<input type="text" name="website" id="id_website" />

>>> print f['name']<input id="id_name" type="text" name="name" maxlength="100" />>>> print f['email']<textarea id="id_email" rows="10" cols="40" name="email"></textarea>>>> print f['website']<input type="text" name="website" id="id_website" />

Page 71: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> f = ProfessorForm()>>> f.is_boundFalse>>> f.is_valid()False

>>> f = ProfessorForm()>>> f.is_boundFalse>>> f.is_valid()False

Page 72: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> f = ProfessorForm({'name':'Kim Doguk', 'email':'[email protected]'})>>> f.is_boundTrue>>> f.is_valid()True

>>> f = ProfessorForm({'name':'Kim Doguk', 'email':'[email protected]'})>>> f.is_boundTrue>>> f.is_valid()True

Page 73: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> f = ProfessorForm({'name':'Oh Youngtaek', 'website': 'http://twitter.com/dongx3'})>>> f.is_boundTrue>>> f.is_valid()False

>>> f = ProfessorForm({'name':'Oh Youngtaek', 'website': 'http://twitter.com/dongx3'})>>> f.is_boundTrue>>> f.is_valid()False

Page 74: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> f = ProfessorForm({'name':'Oh Youngtaek', 'website': 'http://twitter.com/dongx3'})>>> f.is_boundTrue>>> f.is_valid()False

>>> f = ProfessorForm({'name':'Oh Youngtaek', 'website': 'http://twitter.com/dongx3'})>>> f.is_boundTrue>>> f.is_valid()False

Page 75: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> f = ProfessorForm({'name':'Oh Youngtaek', 'website': 'http://twitter.com/dongx3'})>>> f.errors{'email': [u'This field is required.']} >>> f['email'].errors[u'This field is required.']>>> f['name'].errors[]

>>> f = ProfessorForm({'name':'Oh Youngtaek', 'website': 'http://twitter.com/dongx3'})>>> f.errors{'email': [u'This field is required.']} >>> f['email'].errors[u'This field is required.']>>> f['name'].errors[]

Page 76: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> f = ProfessorForm({'name':'Kim Doguk', 'email':'[email protected]'})>>> f.is_valid()True>>> f.cleaned_data{'website': u'', 'name': u'Kim Doguk', 'email': u'[email protected]'}

>>> f = ProfessorForm({'name':'Kim Doguk', 'email':'[email protected]'})>>> f.is_valid()True>>> f.cleaned_data{'website': u'', 'name': u'Kim Doguk', 'email': u'[email protected]'}

Page 77: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

>>> f = ProfessorForm({'name':'Kim Doguk', 'email':'[email protected]'})>>> f.is_valid()True>>> f.cleaned_data{'website': u'', 'name': u'Kim Doguk', 'email': u'[email protected]'}

>>> f = ProfessorForm({'name':'Kim Doguk', 'email':'[email protected]'})>>> f.is_valid()True>>> f.cleaned_data{'website': u'', 'name': u'Kim Doguk', 'email': u'[email protected]'}

Page 78: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# views.pydef add_professor(request): if request.method == 'POST': form = PorfessorForm(request.POST) if form.is_valid(): data = form.cleaned_data p = Professor(name=data['name'], email=data['email'], website=data['website'], job_date=datetime.datetime.now()) p.save() return HttpResponseRedirect('/hell/') else: form = ProfessorForm() return render_to_response('add_professor.html', {'form':form})

# views.pydef add_professor(request): if request.method == 'POST': form = PorfessorForm(request.POST) if form.is_valid(): data = form.cleaned_data p = Professor(name=data['name'], email=data['email'], website=data['website'], job_date=datetime.datetime.now()) p.save() return HttpResponseRedirect('/hell/') else: form = ProfessorForm() return render_to_response('add_professor.html', {'form':form})

Page 79: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# add_professor.html<html><body><h1>Add Professor</h1>{% if form.errors %}<p style="color: red;"> Correct the error{{ form.errors|pluralize }} below.</p>{% endif %}<form method="post"> <table> {{ form.as_table }} <tr><td><input type=‘submit’></td></tr> </table></form></body></html>

# add_professor.html<html><body><h1>Add Professor</h1>{% if form.errors %}<p style="color: red;"> Correct the error{{ form.errors|pluralize }} below.</p>{% endif %}<form method="post"> <table> {{ form.as_table }} <tr><td><input type=‘submit’></td></tr> </table></form></body></html>

Page 80: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 81: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 82: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Creating forms from models

Page 83: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# forms.pyfrom django import formsfrom courses.models import Professor

class ProfessorForm(forms.ModelForm): class Meta: model = Professor

# forms.pyfrom django import formsfrom courses.models import Professor

class ProfessorForm(forms.ModelForm): class Meta: model = Professor

Page 84: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 85: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Users

Page 86: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

UsersPermissionsGroupsMessages

Page 87: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# settings.py

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'courserating.courses',)

# settings.py

INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'courserating.courses',)

Page 88: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

$ python manage.py syncdb $ python manage.py syncdb

Page 89: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

if request.user.is_authenticated(): # Do something for userselse: # Do something for guests

if request.user.is_authenticated(): # Do something for userselse: # Do something for guests

Page 90: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

from django.contrib.auth.decorators import login_required

@login_required def my_view(request): ...

Page 91: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# views.py

def professors(request): profs = Professor.objects.all() return render_to_response('profs.html', {‘profs': profs}, context_instance=RequestContext(request))

# views.py

def professors(request): profs = Professor.objects.all() return render_to_response('profs.html', {‘profs': profs}, context_instance=RequestContext(request))

Page 92: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

{% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %}

{% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %}

Page 93: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# views.pyfrom django.contrib.auth import authenticate, login

def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) # Redirect to a success page. else: # Return a 'disabled account' error message else: # Return an 'invalid login' error message.

# views.pyfrom django.contrib.auth import authenticate, login

def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) # Redirect to a success page. else: # Return a 'disabled account' error message else: # Return an 'invalid login' error message.

Page 94: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# views.pyfrom django.contrib.auth import logout

def logout_view(request): logout(request) # Redirect to a success page.

# views.pyfrom django.contrib.auth import logout

def logout_view(request): logout(request) # Redirect to a success page.

Page 95: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

# urls.py('^accounts/login/$','django.contrib.auth.views.login'),

# urls.py('^accounts/login/$','django.contrib.auth.views.login'),

Page 96: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Not covered

Page 97: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Sessions and CookiesGeneric ViewsDeploying DjangoGenerating Non-HTML django.contribCachingMiddlewareInternationalizationSecurity

Page 98: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Next steps

Page 99: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

http://djangobook.comhttp://

djangoproject.comhttp://

djangosnippets.org

Page 100: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs
Page 101: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

Meet Django

Page 102: 건전지로 달리는 쟝고 세미나. 파트2 Last time MVC Views and URLconfs

실습과제User 가 과목 별점 코멘트

남기는 사이트 만들기