Django girls tutorial
django_app을 Source Root 로 지정을 해준다.
7. 포스트 작성 후 redirect 를 상세 페이지로 변경
def post_add(request):
if request.method == 'POST':
# 요청의 method가 POST일 경우
# 요청받은 데이터를 출력
data = request.POST
# html의 name이 키값
title = data['input_title']
content = data['input_content']
author = User.objects.get(id=1)
# 받은 데이터를 사용해세 Post 객체를 생성
p = Post(title=title, content=content, author=author)
p.save()
# 글 상세화면으로 이동 키워드(post_id)의 인자로 p.id를 전달
return redirect('post_detail', post_id=p.id)
8. form 분리
blog/forms.py 파일 생성하여 작성한다.
from django import forms
# 폼을 자동으로 생성해줌
class PostForm(forms.Form):
title = forms.CharField(max_length=200)
content = forms.CharField(
widget=forms.Textarea
)
# blog/veiw.py
def post_add(request):
# ...
else:
# PostForm형 객체를 만들어 context에 할당
form = PostForm()
context = {
'form': form,
}
return render(request, 'blog/post-add.html', context)
폼 객체로 데이터를 받아 처리하도록 개선한다.
def post_add(request):
# PostForm에 data인자로 request.POST 데이터를 전달해준다
form = PostForm(data=request.POST)
author = User.objects.get(id=1)
# 만약 PostForm객체가 유효할 경우(전달된 데이터의 형식이 PostForm 에 정의한 형식과과 맞을 경우)
if form.is_valid():
#유효한 데이터중 'title' 'content '키의 값을 변수에 할당
title = form.cleaned_data['title']
content = form.cleaned_data['content']
# 받은 데이터를 사용해세 Post 객체를 생성
p = Post(title=title, content=content author=author)
p.save()
else:
return HttpResponse('Form invalid {}'.format(form.errors))
Django tutorial
1. 메인 페이지 만들기
루트 URL(r'^$')
에 polls/와 admin/으로 갈 수 있는 링크 페이지를 구현한다.
- 뷰는 mysite/views/py 안에 def index(request)에 작성
- 템플릿은 templates/index.html을 사용 (polls/, admin/ 연결하는 부분은 {% url %} 태그 쓰지 않고 직접 구현)
- URL은 mystie/urls.py에 작성
# mysite/views.py
from django.shortcuts import render
def index(request):
return render(request, 'index.html')
-
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
-
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Django tutorial Main</title>
</head>
<body>
<h1>Django Tutorial</h1>
<ul>
<li><a href="/polls/">polls application</a></li>
<li><a href="/admin/">Django admin page 이동</a></li>
</ul>
</body>
</html>
2. 절대 주소 변경
3. 네임스페이스
from django.conf.urls import url
from . import views
# 네임스페이스
app_name = 'polls'
urlpatterns = [
url(r'^$', views.index),
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
4. 폼 양식 만들기
def detail(request, question_id):
question = Question.objects.get(id=question_id)
context = {
'question': question,
}
return render(request, 'polls/detail.html', context)
5. POST 객체 shell에 출력하기
def detail(request, question_id):
"""
request.method == 'POST'일 때, 전달받은 데이터 출력
아닐 경우 polls/detail.html을 render
"""
if request.method == 'POST':
print(request.POST)
else:
question = Question.objects.get(id=question_id)
context = {
'question': question,
}
return render(request, 'polls/detail.html', context)
6. POST 객체 choice_id 출력하기
def detail(request, question_id):
"""
request.method == 'POST'일 때,
전달받은 POST객체에서 'choice' 키 값을 HttpResponse로 되돌려준다.
아닐 경우 polls/detail.html을 render
"""
if request.method == 'POST':
# input name으로 설정한 것이 키값 > 그 키로 값을 가져옴
return HttpResponse('{}'.format(request.POST['choice']))
else:
question = Question.objects.get(id=question_id)
context = {
'question': question,
}
return render(request, 'polls/detail.html', context)
7. 선택한 choice의 votes 값 증가
def detail(request, question_id):
"""
request.method == 'POST'일 때, 전달받은 POST객체에서
'choice' 키 값을 HttpResponse로 되돌려준다.
'choice' 키로 전달된 Choice 객체의 id를 이용해서
해당 Choice 객체의 votes 값을 1 늘려주고 데이터베이스 업데이트
완료되면 다시 Question detail 페이지로 이동
1. request.Post['choice']의 값(Choice객체의 ID)을 이용해서 Choice 객체를 가져온다
2. 해당 객체의 votes 값을 늘려주고, 데이터베이스에 변경사항을 업데이트
3. redirect, question_id를 이용해서 detail 페이지로 다시 돌아간다
아닐 경우 polls/detail.html을 render
"""
if request.method == 'POST':
# 1번
choice_id = request.POST['choice']
choice = Choice.objects.get(id=choice_id)
# 2번번
choice.votes += 1
choice.save()
# 3번
return redirect('polls:detail', question_id=question_id)
else:
question = Question.objects.get(id=question_id)
context = {
'question': question,
}
return render(request, 'polls/detail.html', context)
8. result 페이지 생성
# 3번
return redirect('polls:results', question_id=question_id)
else:
question = Question.objects.get(id=question_id)
context = {
'question': question,
}
return render(request, 'polls/detail.html', context)
def results(request, question_id):
# 인자로 주어진 question_id에 해당하는 Question 객체를 context에 담아 render에 보낸다
question = Question.objects.get(id=question_id)
context = {
'question': question,
}
return render(request, 'polls/results.html', context)
과제
- 항목을 선택하지 않고 vote 눌렀을때, 예외처리
- Django Documentation 정리 - Models: Introduction to models