장고 폼
우선 blog
디렉토리 안에 forms.py
파일을 만든다.
xblog
└── forms.py
그리고 아래 코드를 작성한다.
x
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text',)
from django import forms
: forms model을 import 한다.class PostForm(forms.ModelForm)
: PostForm이라는 폼을 만들고 이것이 폼이라는 것을 알려준다.class Meta
: 이 폼을 만들기 위해서 어떤 모델을 써야 하는지 알려준다.
폼과 페이지 링크
blog/templates/blog/base.html
파일에서 page-header
라는 div
class에 링크를 하나 추가한다.
x
<a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>
{% load static %}
<html>
<head>
<title>Django Girls blog</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<link href='//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="{% static 'css/blog.css' %}">
</head>
<body>
<div class="page-header">
<a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>
<h1><a href="/">Django Girls Blog</a></h1>
</div>
<div class="content container">
<div class="row">
<div class="col-md-8">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>
URL
이제 blog/urls.py
파일에 아래 코드를 추가한다.
url(r'^post/new/$', views.post_new, name='post_new'),
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
url(r'^post/new/$', views.post_new, name='post_new'),
]
post_new
view
blog/views.py
파일에서 아래 코드를 추가한다.
from .forms import PostForm
그리고 view에 추가한다.
def post_new(request):
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
템플릿
blog/template/blog
디렉토리에 post_edit.html
파일을 만들고 아래와 같이 작성한다.
x
{% extends 'blog/base.html' %}
{% block content %}
<h1>New post</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
{{ form.as_p }}
: 폼을 보이게한다.{% csrf_token %}
: 이것은 폼의 보안을 위해서 넣어야 되는 내용이다.
그리고 서버를 실행시켜서 폼을 확인해본다.
하지만 아직 글이 추가되지는 않는다.
폼 저장하기
아까 작성했던 뷰를 다시본다.
def post_new(request):
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
폼을 제출할 때, 같은 뷰를 불러온다. 이때 request
에는 입력했던 데이터를 가지고 있는데, request.POST
가 이 데이터를 가지고 있다. HTML에서 <form>
정의에 method="POST"
라는 속성이 있었는데, 이렇게 POST로 넘겨진 폼 필드의 값은 request.POST
에 저장된다.
이제 view에서 두 가지 상황으로 나누어 처리한다.
- 처음 페이지에 접속했을 때 : 새 글을 쓸 수 있게끔 폼이 비어져야 된다.
- 폼에 입력된 데이터를 view 페이지로 가지고 올 때 : 여기서 조건문을 추가시켜야 한다.
x
if request.method == "POST":
[...]
else:
form = PostForm()
이제 [...]
부분에 코드를 추가할 차례다. 만약 method
가 POST
라면, 폼에서 받은 데이터를 PostForm
으로 넘겨줘야 되므로 이렇게 작성하면 된다.
form = PostForm(request.POST)
다음으로 폼에 있는 값들이 올바른지 확인하기 위해서 form.is_valid()
을 사용한다.
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
commit=False
는 넘겨진 데이터를 바로 Post
모델에 저장하지 말라는 뜻이다. 왜냐하면 여기서는 작성자 정보를 추가하기 위해서이다.
그 다음 from 라인에 다음 코드를 추가한다.
xxxxxxxxxx
from django.shortcuts import redirect
그리고 마지막으로 아래 코드를 입력한다.
xxxxxxxxxx
return redirect('post_detail', pk=post.pk)
xxxxxxxxxx
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
서버를 실행시키고 잘 작동하는지 확인한다.
폼 수정하기
blog/templates/blog/post_detail.html
파일을 열어서 아래 내용을 추가한다.
x
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
xxxxxxxxxx
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
<h1>{{ post.title }}</h1>
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endblock %}
blog/urls.py
파일에 다음 코드를 추가한다.
xxxxxxxxxx
url(r'^post/(?P<pk>\d+)/edit/$', views.post_edit, name='post_edit'),
blog/views.py
파일에 밑의 코드를 추가한다.
x
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
그리고 서버를 실행시켜서 잘 작동되는지 확인한다.
'Python > Django' 카테고리의 다른 글
장고 걸즈 튜토리얼 따라하기 13 - 어플리케이션 확장 (0) | 2019.01.05 |
---|---|
장고 걸즈 튜토리얼 따라하기 12 - 템플릿 확장 (0) | 2019.01.04 |
장고 걸즈 튜토리얼 따라하기 11 - CSS (0) | 2019.01.03 |
장고 걸즈 튜토리얼 따라하기 10 - 장고 템플릿 (0) | 2019.01.02 |
장고 걸즈 튜토리얼 따라하기 9 - 템플릿 동적 데이터 (0) | 2018.12.27 |