FBV : 함수 기반 뷰
예시)
url.py 와 같이 url에 /fbv/ 입력 시 함수 호출 -> views.py 에 function_view 에 대한 정의 -> view.html 표시
url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('url/', url_view),
path('url/<str:username>/', url_parameter_view),
path('fbv/', function_view)
]
views.py
def function_view(request):
print(f'request.method : {request.method}')
print(f'request.GET : {request.GET}')
print(f'request.POST : {request.POST}')
return render(request, 'view.html')
view.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>Document</title>
</head>
<body>
<a href="/fbv/">새로고침</a><br>
<form action="" method="GET">
<input type="text" name="var">
<input type="submit" value="GET 제출">
</form>
<form action="" method="POST"> {% csrf_token %}
<input type="text" name="var">
<input type="submit" value="POST 제출">
</form>
</body>
</html>
CBV : 클래스 기반 뷰
예시) url.py 에서 class_view.as_view 호출 -> class_view는 ListView를 상속하여 속성만 지정 -> cbv_view.html 표시
url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('url/', url_view),
path('url/<str:username>/', url_parameter_view),
path('fbv/', function_view),
path('cbv/', class_view.as_view()),
view.py
class class_view(ListView):
model = Post
template_name ='cbv_view.html'
cbv_view.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>Document</title>
</head>
<body>
{% for object in object_list %}
<p>{{ object }}</p>
{% endfor %}
</body>
</html>