"게시판만들기 3. 게시글 쓰기"의 두 판 사이의 차이
둘러보기로 가기
검색하러 가기
(새 문서: == 개요 == 게시글은 써야 맛이지. == 글쓰기 버튼 만들기 == 글 목록이 보여주는 board/list.html의 표 아래에 다음을 추가한다.<syntaxhighlight lang=...) |
|||
19번째 줄: | 19번째 줄: | ||
== view 작성 == | == view 작성 == | ||
board.views.py에 다음과 같은 함수를 추가한다.[자, 여기서부터...]<syntaxhighlight lang="python"> | board.views.py에 다음과 같은 함수를 추가한다.[자, 여기서부터...]<syntaxhighlight lang="python"> | ||
− | |||
− | |||
def create(request): | def create(request): | ||
− | if request.method == 'POST': #포스트로 요청이 들어온다면... 글을 올리는 기능. | + | from django.shortcuts import redirect |
− | form = | + | from .forms import WritingForm |
− | if form.is_valid(): #문제가 없으면 다음으로 진행. | + | from django.utils import timezone # 시간입력용 |
− | + | if request.method == 'POST': # 포스트로 요청이 들어온다면... 글을 올리는 기능. | |
− | + | form = WritingForm(request.POST) # 폼을 불러와 내용입력을 받는다. | |
− | + | if form.is_valid(): # 폼에서 에러처리. 문제가 없으면 다음으로 진행. | |
− | + | writing = form.save(commit=False) # commit=False는 저장을 잠시 미루기 위함.(입력받는 값이 아닌, view에서 다른 값을 지정하기 위해) | |
− | + | writing.author = request.user # 추가한 속성 author 적용 | |
− | return redirect(' | + | writing.create_date = timezone.now() #현재 작성일시 자동저장 |
+ | writing.save() | ||
+ | return redirect('board:list') #작성이 끝나면 목록화면으로 보낸다. | ||
else: #포스트 요청이 아니라면.. form으로 넘겨 내용을 작성하게 한다. | else: #포스트 요청이 아니라면.. form으로 넘겨 내용을 작성하게 한다. | ||
− | form = | + | form = WritingForm() |
− | context = {'form': form} #폼에서 오류가 있으면 오류의 내용을 담아 create.html로 넘긴다. | + | context = {'form': form} # 폼에서 오류가 있으면 오류의 내용을 담아 create.html로 넘긴다. |
− | #없으면 그냥 form 작성을 위한 객체를 넘긴다. | + | # 없으면 그냥 form 작성을 위한 객체를 넘긴다. |
− | return render(request, 'create.html', context) | + | return render(request, 'board/create.html', context) |
+ | </syntaxhighlight> | ||
+ | |||
+ | == form 작성 == | ||
+ | board/forms.py를 만든 후 다음과 같이 입력한다.<syntaxhighlight lang="python"> | ||
+ | from django import forms | ||
+ | from .models import Writing # 폼을 적용할 모델을 불러온다. | ||
+ | |||
+ | class WritingForm(forms.ModelForm): | ||
+ | class Meta: | ||
+ | model = Writing # 사용할 모델 | ||
+ | fields = ['subject', 'content'] # 폼으로 입력할 필드를 입력해준다. | ||
+ | # fields에 '__all__'을 따옴표까지 함께 넣어주면 모든 필드를 가져오라는 명령이 된다. | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | == template 작성 == | ||
+ | board/create.html을 만들고 body 안에 다음이 들어가게 한다.<syntaxhighlight lang="html+django"> | ||
+ | <body> | ||
+ | |||
+ | <form action="{% url 'board:create' %}" method="POST"> | ||
+ | {% csrf_token %} | ||
+ | {{ form}} | ||
+ | <input type="submit" value="제출"> | ||
+ | </form> | ||
+ | |||
+ | </body> | ||
</syntaxhighlight> | </syntaxhighlight> | ||
[[분류:장고 기능구현(초급)]] | [[분류:장고 기능구현(초급)]] |
2021년 6월 22일 (화) 19:58 판
1 개요
게시글은 써야 맛이지.
2 글쓰기 버튼 만들기
글 목록이 보여주는 board/list.html의 표 아래에 다음을 추가한다.
<a href="{% url 'board:create' %}" class="btn btn-primary">글쓰기</a>
3 url 매핑
3.1 board.urls에 추가
urlpatterns 안에 다음을 추가한다.
urlpatterns = [
path('create/', views.create, name='create'),
]
4 view 작성
board.views.py에 다음과 같은 함수를 추가한다.[자, 여기서부터...]
def create(request):
from django.shortcuts import redirect
from .forms import WritingForm
from django.utils import timezone # 시간입력용
if request.method == 'POST': # 포스트로 요청이 들어온다면... 글을 올리는 기능.
form = WritingForm(request.POST) # 폼을 불러와 내용입력을 받는다.
if form.is_valid(): # 폼에서 에러처리. 문제가 없으면 다음으로 진행.
writing = form.save(commit=False) # commit=False는 저장을 잠시 미루기 위함.(입력받는 값이 아닌, view에서 다른 값을 지정하기 위해)
writing.author = request.user # 추가한 속성 author 적용
writing.create_date = timezone.now() #현재 작성일시 자동저장
writing.save()
return redirect('board:list') #작성이 끝나면 목록화면으로 보낸다.
else: #포스트 요청이 아니라면.. form으로 넘겨 내용을 작성하게 한다.
form = WritingForm()
context = {'form': form} # 폼에서 오류가 있으면 오류의 내용을 담아 create.html로 넘긴다.
# 없으면 그냥 form 작성을 위한 객체를 넘긴다.
return render(request, 'board/create.html', context)
5 form 작성
board/forms.py를 만든 후 다음과 같이 입력한다.
from django import forms
from .models import Writing # 폼을 적용할 모델을 불러온다.
class WritingForm(forms.ModelForm):
class Meta:
model = Writing # 사용할 모델
fields = ['subject', 'content'] # 폼으로 입력할 필드를 입력해준다.
# fields에 '__all__'을 따옴표까지 함께 넣어주면 모든 필드를 가져오라는 명령이 된다.
6 template 작성
board/create.html을 만들고 body 안에 다음이 들어가게 한다.
<body>
<form action="{% url 'board:create' %}" method="POST">
{% csrf_token %}
{{ form}}
<input type="submit" value="제출">
</form>
</body>