https://docs.djangoproject.com/search/?q=forms&release=1
와 같은 형식의 URL이 생성되는 경우를 볼 수 있다.from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label="Your name", max_length=100)
Form 인스턴스에는 모든 필드에 대해 유효성 검사 루틴을 실행하는 is_valid()
메소드가 있다. 이 메소드가 호출될 때 만약 모든 필드가 유효한 데이터를 포함한다는 전제가 깔려있다면 아래와 같은 작업이 실행된다.
cleaned_data
속성으로 넣는다.class PollCreateForm(forms.Form):
topic = forms.CharField(max_length=50, label='투표 주제')
options = forms.CharField(max_length=300, label='투표 옵션')
def create_poll(request):
if request.method == "POST":
form = PollCreateForm(request.POST)
if form.is_valid():
title = form.cleaned_data['topic']
options = form.cleaned_data['options'].split(",") # split의 형태 > List
topic = Topic(title=title)
topic.save()
for item in options:
Option.objects.create(name=item, topic=topic)
return HttpResponseRedirect('/votes/polls/')
else:
# POST 미접근시, 기존처럼 새로운 폼을 아무것도 전달하지 않고 인스턴스를 생성해서 그대로 템플릿의 context dictionary로 넘겨주면 빈 폼이 렌더링됴ㅚㅁ
form = PollCreateForm()
context = {
'create_form': form
}
return render(request, 'votes/create_poll.html', context)
csrf_token
이라고 하기 때문에 csrf_token
구문은 이 token을 출력하는 역할을 한다.{% csrf_token %}
을 템플릿 파일에 넣는 것이다.form을 사용해서 렌더링할 때 폼의 형태가 원하는대로 나오지 않아서 폼의 출력 결과를 좀 이쁘게 정리하고픈 순간이 있을 것이다. Django에서는 폼의 형태를 정리해주는 것도 제공한다.