본문 바로가기

Python/Django

[Django] Class based View - FormView

이번에는 클래스 기반의 뷰중 FormView에 대해서 알아보겠습니다.

 

1. forms  생성

2. views 에 forms.py 에서 생성한 form 을 임포트(from classroom.forms import ContactForm), 물론 FormView 도 추가.

3. views 에 FormView 클래스 생성(폼 클래스 연결, 템플릿 연결, 정상 URL 연결, 폼데이터 처리)

 

 

forms.py 생성 - ModelForm 이 아닌 일반 폼으로 구현예정.

 

from django import forms

class ContactForm(forms.Form):
    name = forms.CharField()
    message = forms.CharField(widget=forms.Textarea)

 

 

views.py 수정

 

from django.shortcuts import render
from django.views.generic import TemplateView, FormView
from classroom.forms import ContactForm

# Create your views here.
# def home_view(request):
#     return render(request, 'classroom/home.html')

class HomeView(TemplateView):
    template_name = 'classroom/home.html'

class ThankYouView(TemplateView):
    template_name = 'classroom/thank_you.html'
    
class ContactFormView(FormView): # <=== 추가 부분
    # 1. 폼 클래스 연결, 
    form_class = ContactForm # 인스턴스 생성하기전에 연결만 함.
    # 2. 폼과 연결할 template_name 설정
    template_name = 'classroom/contact.html' 

    # 3. 정상일때 이동할 URL 설정.
    # success URL?, URL is not a template.html
    success_url = '/classroom/thank_you/' 
    # 여기서 reverse 를 사용하고 싶다면 reverse_lazy() 를 사용해야 한다(lazy는 object 리턴). 외울것.
    # success_url = reverse_lazy('classroom:thank_you')

    # what to do with form?
    def form_valid(self, form):
        print(form.cleaned_data)
        # ContactForm(reques.POST)
        return super().form_valid(form)

 

 

templates/classroom/contact.html 생성

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact</title>
</head>
<body>
    <h1>Form View Template (contact.html)</h1>
    <form action="" method="post">
        {% csrf_token %}
        {{form.as_p}}
        <input type="submit" value="Submit">
    </form>
</body>
</html>

 

 

./classroom/urls.py 수정

 

from django.urls import path
from . import views

app_name = 'classroom'

# domain.com/classroom
urlpatterns = [
    # path('', views.home_view, name='home'), # path expects a function!
    path('', views.HomeView.as_view(), name='home'), # 클래스를 가지고 경로에 대한 함수를 반환
    path('thank_you/', views.ThankYouView.as_view(), name='thank_you'), 
    path('contact/', views.ContactFormView.as_view(), name='contact'), 
]

 

 

home.html 수정

 

<body>
    <h1>Welcome to home.html</h1>
    <ul>
        <li>
            <a href="{% url 'classroom:thank_you' %}">THANK YOU PAGE LINK</a>
        </li>
        <li>
            <a href="{% url 'classroom:contact' %}">CONTACT PAGE LINK</a>
        </li>
    </ul>
</body>

 

 

실행화면

 

 

 

 

 

 

 

로그 확인

 

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[16/Dec/2022 17:52:48] "GET /classroom/ HTTP/1.1" 200 498
[16/Dec/2022 17:53:05] "GET /classroom/contact/ HTTP/1.1" 200 823
{'name': '홍길동', 'message': '홍길동에'}
[16/Dec/2022 17:53:36] "POST /classroom/contact/ HTTP/1.1" 302 0
[16/Dec/2022 17:53:36] "GET /classroom/thank_you/ HTTP/1.1" 200 286