320x100
# 첫번째 파일
school > classroom > views.py
from django.shortcuts import render
# 이것은 내가 찾고 있는 URL의 실제 이름을 리턴한다.
# reverse는 string타입을 리턴하고 reverse_lazy는 object 타입을 리턴한다.
# 또한 success_url 을 사용하는경우, reverse_lazy를 사용한다.
from django.urls import reverse, reverse_lazy
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):
form_class = ContactForm
template_name = 'classroom/contact.html'
# URL NOT a template.html
success_url = reverse_lazy('classroom:thank_you')
# what to do with form?
def form_valid(self, form):
print(form.cleaned_data)
# ContactForm(request.POST)
return super().form_valid(form)
# 두번째 파일
school > classroom > urls.py
from django.urls import path
from .views import HomeView, ThankYouView, ContactFormView
app_name = 'classroom'
# domain.com/classroom/
urlpatterns = [
path('', HomeView.as_view(), name = 'home'), # path expects a function
path('thank_you/', ThankYouView.as_view(), name = 'thank_you'), # path expects a function
path('contact/', ContactFormView.as_view(), name = 'contact')
]
# 세번째 파일
school > classroom > templates > classroom > home.html
<h1>welcome to home.html</h1>
<li>
<ul>
<a href='{% url 'classroom:thank_you' %}'>Thank you page link</a>
</ul>
<ul>
<a href='{% url 'classroom:contact' %}'>Contact form page link</a>
</ul>
</li>
# 네번째 파일
school > classroom > templates > classroom > contact.html
<h1>Form View Template (contact.html)</h1>
<form method='POST'>
{% csrf_token %}
{{form.as_p}}
<input type='submit' value='Submit'>
</form>
# 다섯번째 파일
school > classroom > forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
message = forms.CharField(widget=forms.Textarea)
300x250
'개발일지 > Django' 카테고리의 다른 글
Django - cbv ListView (0) | 2022.10.01 |
---|---|
Django - cbv CreateView (0) | 2022.10.01 |
Django - cbv template view (0) | 2022.10.01 |
Django - ModelForms 커스터마이징 (0) | 2022.10.01 |
Django - ModelForms (0) | 2022.10.01 |