19번째 줄: |
19번째 줄: |
| == view 작성 == | | == view 작성 == |
| board.views.py에 다음과 같은 함수를 추가한다.[자, 여기서부터...]<syntaxhighlight lang="python"> | | board.views.py에 다음과 같은 함수를 추가한다.[자, 여기서부터...]<syntaxhighlight lang="python"> |
− | from .forms import
| |
− |
| |
| def create(request): | | def create(request): |
− | if request.method == 'POST': #포스트로 요청이 들어온다면... 글을 올리는 기능. | + | from django.shortcuts import redirect |
− | form = QuestionForm(request.POST) #폼을 불러와 내용입력을 받는다. | + | from .forms import WritingForm |
− | if form.is_valid(): #문제가 없으면 다음으로 진행. | + | from django.utils import timezone # 시간입력용 |
− | question = form.save(commit=False) #commit=False는 저장을 잠시 미루기 위함.(입력받는 값이 아닌, view에서 다른 값을 지정하기 위해) | + | if request.method == 'POST': # 포스트로 요청이 들어온다면... 글을 올리는 기능. |
− | question.author = request.user # 추가한 속성 author 적용 | + | form = WritingForm(request.POST) # 폼을 불러와 내용입력을 받는다. |
− | question.create_date = timezone.now() #현재 작성일시 자동저장 | + | if form.is_valid(): # 폼에서 에러처리. 문제가 없으면 다음으로 진행. |
− | question.profile = request.user.schoolprofile # 유저가 현재 사용하는 프로필 | + | writing = form.save(commit=False) # commit=False는 저장을 잠시 미루기 위함.(입력받는 값이 아닌, view에서 다른 값을 지정하기 위해) |
− | question.save()
| + | writing.author = request.user # 추가한 속성 author 적용 |
− | return redirect('pool:list') #작성이 끝나면 목록화면으로 보낸다. | + | writing.create_date = timezone.now() #현재 작성일시 자동저장 |
| + | writing.save() |
| + | return redirect('board:list') #작성이 끝나면 목록화면으로 보낸다. |
| else: #포스트 요청이 아니라면.. form으로 넘겨 내용을 작성하게 한다. | | else: #포스트 요청이 아니라면.. form으로 넘겨 내용을 작성하게 한다. |
− | form = QuestionForm() | + | 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> |
| [[분류:장고 기능구현(초급)]] | | [[분류:장고 기능구현(초급)]] |