In django, there’re three terms about views. They’re:
- Function-Based Views (FBV)
- Class-Based Views (CBV)
- Generic Class-Based Views (GCBV)
FBV
A FBV is the simplest representation of a Django view: it’s just a function that receives an HttpRequest object and returns an HttpResponse.
views.py:1
2
3
4
5
6
7
8
9def new_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form.save()
return redirect('post_list')
else:
form = PostForm()
return render(request, 'new_post.html', {'form': form})
urls.py1
2
3urlpatterns = [
url(r'^new_post/$', views.new_post, name='new_post'),
]
CBV
A CBV is every Django view defined as a Python class that extends the django.views.generic.View
abstract class. A CBV essentially is a class that wraps a FBV. CBVs are great to extend and reuse code.
A CBV is a view that extends the View class. The main difference here is that the requests are handled inside class methods named after the HTTP methods, such as get, post, put, head, etc.
So, here we don’t need to do a conditional to check if the request is a POST or if it’s a GET. The code goes straight to the right method. This logic is handled internally in the View class.
views.py1
2
3
4
5
6
7
8
9
10
11
12
13from django.views.generic import View
class NewPostView(View):
def post(self, request):
form = PostForm(request.POST)
if form.is_valid():
form.save()
return redirect('post_list')
return render(request, 'new_post.html', {'form': form})
def get(self, request):
form = PostForm()
return render(request, 'new_post.html', {'form': form})
or make views.py like below:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16from django.views.generic import View
class NewPostView(View):
def render(self, request):
return render(request, 'new_post.html', {'form': self.form})
def post(self, request):
self.form = PostForm(request.POST)
if self.form.is_valid():
self.form.save()
return redirect('post_list')
return self.render(request)
def get(self, request):
self.form = PostForm()
return self.render(request)
urls.py1
2
3urlpatterns = [
url(r'^new_post/$', views.NewPostView.as_view(), name='new_post'),
]
GCBV
GCBVs are built-in CBVs that solve specific problems such as listing views, create, update, and delete views.
When working with GCBV, it’s always good to have the ccbv.co.uk opened for quick reference.
views.py (CreateView)
1 | from django.views.generic import CreateView |
urls.py1
2
3urlpatterns = [
url(r'^new_post/$', views.NewPostView.as_view(), name='new_post'),
]
Update View
1 | from django.shortcuts import redirect |