question_detail.html
<h1>{{ question.subject }}</h1>
<div>
{{ question.content }}
</div>
<form action="{% url 'pybo:answer_create.id %}" method="post">
{% csrf_token %}
<textarea name="content" id="content" rows="15"></textarea>
<input type="submit" value="답변등록">
</form>
{% csrf_token %}
- 보안 관련 항목으로 Post 요청시 form 태그에 csrf_token이 없으면 장고는 에러pybo/urls.py
from django.urls import path
from . import views
app_name = 'pybo'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('answer/create/<int:qustion_id>', views.answer_create, name='answer_create'),
]
→ 매핑 등록
pybo/views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Question
(... 생략 ...)
def answer_create(request, question_id):
question = get_object_or_404(Question, pk=question_id)
question.answer_set.create(content=request.POST.get('content'), create_date=timezone.now()) #답변 생성 (FK 이용)
return redirect('pybo:detail', question_id=question.id)
pybo/question_detail.html
<h1>{{ question.subject }}</h1>
<div>
{{ question.content }}
</div>
<h5>{{ question.answer_set.count }}개의 답변이 있습니다.</h5> #답변의 개수
<div>
<ul>
{% for answer in question.answer_set.all %}
<li>{{ answer.content }}</li>
{% endfor %}
</ul>
</div>
<form action="{% url 'pybo:answer_create' question.id %}" method="post">
{% csrf_token %}
<textarea name="content" id="content" rows="15"></textarea>
<input type="submit" value="답변등록">
</form>
static
directorymkdir static
) 후 config/settings.py에 등록(... 생략 ...)
STATIC_URL = 'static/'
STATICFILES_DIRS = [
BASE_DIR / 'static',
]
(... 생략 ...)
static/style.css
textarea {
width:100%;
}
input[type=submit] {
margin-top:10px;
}
question_detail.html
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">
(... 생략 ...)
{% load static %}
- 최상단에 삽입해 {% static ... %}
와 같은 템플릿 태그를 사용할수 있도록 함.