forms
: 인터페이스를 만들 수 있음
blog/forms.py
- forms.py 생성
from django import forms
from .models import Post
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text',)
폼과 페이지 링크
blog/templates/blog/base.html
- a태그 추가
<body>
<div class="page-header">
<a href="{% url 'post_new' %}" class="top-menu"><span class="glyphicon glyphicon-plus"></span></a>
<h1><a href="/">Blog Name</a></h1>
</div>
URL
blog/urls.py
- path('post/new/', views.post_new, name='post_new'), 추가
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'),
]
post_new view
blog/views.py
- view 추가
from .forms import PostForm
def post_new(request):
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
템플릿
blog/templates/blog/post_edit.html
{% 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 %}
폼 작성
blog/views.py
from django.shortcuts import redirect
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
- a태그 추가
{% endif %}
<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a>
<h1>{{ post.title }}</h1>
blog/urls.py
- 경로 지정
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
blog/views.py
- 메소드 작성
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, 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})
https://tutorial.djangogirls.org/ko/django_forms/
'Languages > Python' 카테고리의 다른 글
[Python] anaconda3 jupyter notebook error (0) | 2020.09.02 |
---|---|
[Django] 애플리케이션 확장 - Djangogrils (0) | 2020.07.31 |
[Django] Template extending - Djangogirls (0) | 2020.07.31 |
[Django] templates 꾸미기 - Djangogirls (0) | 2020.07.30 |
[Django] Template tags - Djangogirls (0) | 2020.07.30 |