Django
14. 폼 클래스
테니드2
2021. 4. 8. 21:23
- polls/forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='너의 이름은', max_length=100)
- polls/views.py
def get_name(request):
# POST 방식이면, 데이터가 담긴 제출된 폼으로 간주합니다.
if request.method == 'POST':
# request에 담긴 데이터로, 클래스 폼을 생성합니다.
form = NameForm(request.POST)
# 폼에 담긴 데이터가 유효한지 체크합니다.
if form.is_valid():
# 폼 데이터가 유효하면, 데이터는 clean_data로 복사됩니다.
new_name = form.cleaned_data['your_name']
# 로직에 따라 추가적인 처리를 합니다.
print(new_name)
# 새로운 URL로 리다이렉션시킵니다.
return HttpResponseRedirect(reverse('polls:index'))
# POST 방식이 아니면(GET 요청임).
# 빈 폼을 사용자에게 보여줍니다.
else:
form = NameForm()
return render(request, 'polls/name.html', {'form': form})
- polls/urls.py
path('yourname/', views.get_name, name='yourname')
- polls/template/polls/name.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="{% url 'polls:yourname' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="제출">
</form>
</body>
</html>
- 결과 화면
출처: 한빛미디어, Django로 배우는 쉽고 빠른 웹 개발 파이썬 웹 프로그래밍