Class based views

             keeping your code classy
So, What is a view?
So, What is a view?
from django.http import HttpResponse

def current_datetime(request):
    html = "<html><h1>Hello, Django Cali!!!!!.</h1></html>" 
    return HttpResponse(html)

URLconf

Et voilà, a Web response magically appeared!
Class-Based Views
not a function, an object!
                         (and all that it implies)
Class-Based Views
code related to specific HTTP methods (GET, POST, etc.) addressed by separate methods instead of conditional branching.
Class-Based Views
code related to specific HTTP methods (GET, POST, etc.) addressed by separate methods instead of conditional branching.
def current_datetime(request):
    if request.method == 'GET':
        do_something()
    elif request.method == 'POST':
        do_something_else()
from django.views.generic import View

class MyView(View):

    def get(self, request, *args, **kwargs):
        do_something()
    def post(self, request, *args, **kwargs):
        do_something_else()
FROM
TO
Stay classy!
Class-Based Views
Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components!!!!!!
Remember Django's philosophy,Don’t repeat yourself!
Class-Based Views
Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components!!!!!!
from djangocali.models import Attendee

def DjangoCaliAttendeeDetail(request, *args, **kwargs):
    if request.method == 'GET':
        if not request.user.is_authenticated():
            return HttpResponseForbidden()
        ateendee_slug = kwargs['slug']
        object = Attendee.objects.get(slug=ateendee_slug)
        context = do_something(object)
        return render(request, 'attendee_detail.html', context)
Class-Based Views
Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components!!!!!!
from django.views.generic import View
from django.views.generic.detail import SingleObjectMixin
from djangocali.models import Attendee

class DjangoCaliAttendeeDetail(SingleObjectMixin, View):
    """shows the information about the requested Attendee"""
    model = Attendee

    def get(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseForbidden()

        # Look up the Attendee that is related to the request.
        self.object = self.get_object()
        context = do_something(self.object)

        return render(request, 'attendee_detail.html', context)
Class-Based Views
Another object oriented technique:
subclassing and overriding attributes and methods in
the subclass
from django.http import HttpResponse
from django.views.generic import View

class GreetingView(View):
    greeting = "Good Day"

    def get(self, request):
        return HttpResponse(self.greeting)


class MorningGreetingView(GreetingView):
    greeting = "Morning to ya"

## another option

urlpatterns = [
    url(r'^about/', GreetingView.as_view(greeting="G'day")),
]
Class-Based Views
General usage
URL dispatcher
view
class-based
 view
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^djangocali/attendee/$',
        views.attendee_view),
    url(r'^djangocali/history/$',
        views.history_view),
    url(r'^djangocali/someurl/$',
        views.some_view),
]
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^djangocali/attendee/$',
        views.AttendeeView.as_view()),
    url(r'^djangocali/history/$',
        views.HistoryView.as_view()),
    url(r'^djangocali/someurl/$',
        views.SomeView.as_view()),
]
Class-Based Views
General usage
URL dispatcher
class-based
 view
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^djangocali/attendee/$',
        views.AttendeeView.as_view()),
    url(r'^djangocali/history/$',
        views.HistoryView.as_view()),
    url(r'^djangocali/someurl/$',
        views.SomeView.as_view()),
]
.as_view creates an instance of your class and calls its dispatch() method.
dispatch looks at the request to determine whether it is a GET, POST, etc, and relays the request to a matching method if one is defined, or raises HttpResponseNotAllowed if not
Class-Based Views
General usage
Decorators
In the URLconf
In the definition
from django.utils.decorators import\ 
method_decorator
from django.views.generic import View
from django.views.decorators.cache import\ 
cache_page

class SomeView(View):
    @method_decorator(cache_page(5))
    def dispatch(self, *args, **kwargs):
        return super(
        SomeView, self).dispatch(*args,**kwargs)

// other option, decorate the class itself 
// at name you can define the method to decorate

@method_decorator(cache_page(5),name='dispatch')
class SomeView(View):
from django.conf.urls import url
from django.views.decorators.cache import\
cache_page
from . import views

urlpatterns = [
    url(r'^djangocali/attendee/$',
        views.AttendeeView.as_view()),
    url(r'^djangocali/history/$',
        views.HistoryView.as_view()),
    url(r'^djangocali/someurl/$',
      cache_page(5)(views.SomeView.as_view())),
]
Some Class-Based Views
from django.http import HttpResponse
from django.views.generic import View, TemplateView
from djangocali.models import Attendee

class SomeView(View):

    def get(self, request, *args, **kwargs):
        html = "<html><h1>Hello, \
                Django Cali!!!!!.</h1></html>"
        return HttpResponse(html)


class AttendeeView(TemplateView):

    template_name = "Attendee.html"

    def get_context_data(self, **kwargs):
        context = super(AttendeeViewView,
                        self).get_context_data(**kwargs)
        context['attendees'] = Attendee.objects.all()
        return context
from django.views.generic.edit import UpdateView,CreateView
from django.views.generic.edit import DeleteView
from django.core.urlresolvers import reverse_lazy
from djangocali.models import Attendee

class AttendeeCreateView(CreateView):
    model = Attendee
    fields = ['name','email']


class AttendeeUpdateView(UpdateView):
    model = Attendee
    fields = ['email']
    template_name_suffix = '_update_form'


class AttendeeDeleteView(DeleteView):
    model = Attendee
    success_url = reverse_lazy('home')
    def get_object(self, queryset=None):
        obj =Attendee.objects.get(uuid=self.kwargs['uuid'])
        return obj
Some Class-Based Views
from django.views.generic.edit import UpdateView,CreateView
from django.views.generic.edit import DeleteView
from django.core.urlresolvers import reverse_lazy
from djangocali.models import Attendee

class AttendeeCreateView(CreateView):
    model = Attendee
    fields = ['name','email']


class AttendeeUpdateView(UpdateView):
    model = Attendee
    fields = ['email']
    template_name_suffix = '_update_form'


class AttendeeDeleteView(DeleteView):
    model = Attendee
    success_url = reverse_lazy('home')
    def get_object(self, queryset=None):
        obj =Attendee.objects.get(uuid=self.kwargs['uuid'])
        return obj



<!--CreateView html example-->

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Create" />
</form>

<!--UpdateView html example-->

<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Update" />
</form>


<!--Delete html example-->

<form action="" method="post">{% csrf_token %}
    <p>Are you sure you want to delete "{{ object }}"?</p>
    <input type="submit" value="Confirm" />
</form>
And more Class-Based Views!!
https://ccbv.co.uk/
https://docs.djangoproject.com/en/1.8/ref/class-based-views/
Need more info?
Questions?

classbasedviews

By Jose Ariza

classbasedviews

  • 1,662