Reputation: 309
Why would one use a Base view in Django when this
from django.http import HttpResponse
from django.views import View
class MyView(View):
def get(self, request, *args, **kwargs):
return HttpResponse('Hello, World!')
can be written as
def get(request):
return HttpResponse('Hello, World!')
What is the advantage of the Base view vs the function view?
Upvotes: 0
Views: 496
Reputation: 15926
All sorts of reasons.
You want to make use of a specialized view, like the TemplateView
mentioned by @pythonista that makes it a lot easier for you to write your view. e.g.,
class MyTemplateView(TemplateView):
template_name = 'template.html'
You want to have some isolation when you have similar behavior. For example, you want a class-based View to handle both the form rendering and the form post:
class MyFormView(TemplateView):
template_name = 'form.html'
def get(self, request, *args, **kwargs):
return super(MyFormView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs:
value1 = request.POST.get('value1')
value2 = request.POST.get('value2')
# handle the post values
return super(MyFormView, self).get(request, *args, **kwargs)
You have REST endpoint and you’d like to isolate all of the code for GET/POST/PUT/DELETE in a single class-based view.
class RestEndpoint(View):
def __init__(self):
super(RestEndpoint, self).__init__()
self.model = MyModel
def get(request, n_id, *args, **kwargs):
x = self.model.objects.get(id=n_id)
return JsonResponse(x.to_json())
def put(self, request, *args, **kwargs):
data = json.loads(request.body)
x = self.model(**data)
x.save()
return JsonResponse(x.to_json())
def post(self, request, n_id, *args, **kwargs):
data = json.loads(request.body)
x = self.model.objects.get(id=n_id)
for key, value in data.items():
setattr(x, key, value)
x.save()
return JsonResponse(x.to_json())
def delete(self, request, n_id, *args, **kwargs):
self.model.objects.filter(id=n_id).delete()
return JsonResponse({})
You just prefer using classes instead of functions, e.g., so that you can create your own fun base views and reuse code with inheritance.
Upvotes: 3