Slide 1

Slide 1 text

ANDREW PINKHAM TOPIC DATE AUTHOR SEPTEMBER 2015 VIEWS: FUNCTIONS, CLASSES & GENERICS DJANGOCON US 2015

Slide 2

Slide 2 text

$ whoami Software Engineer Freelance Consultant Technical Instructor Andrew Pinkham Hi, I’m

Slide 3

Slide 3 text

AUTHOR OF DJANGO UNLEASHED AVAILABLE FOR PREORDER; SHIPS DECEMBER 2015

Slide 4

Slide 4 text

Answers today: Django handles HTTP for me! Why do I have to worry about it? When is Django deprecating function views? Aren’t all class-based views generic? How do I choose what kind of view to use?

Slide 5

Slide 5 text

$ ls views 1_fundamentals 2_views 3_tools

Slide 6

Slide 6 text

$ ls views 1_fundamentals -> problem, meet solution 2_views -> examining the solution 3_tools -> making the solution easier

Slide 7

Slide 7 text

$ less views/1_fundamentals What is a callable? What is HTTP, anyway? Django's HTTP request/response cycle A view’s purpose

Slide 8

Slide 8 text

$ less views/2_views A Brief History of Views Functions Views Class Based Views Generic Class Based Views

Slide 9

Slide 9 text

$ less views/3_tools Enhance! When to Use What

Slide 10

Slide 10 text

afrg.co/views

Slide 11

Slide 11 text

PYTHON CALLABLES UNDERSTANDING THE PROBLEM

Slide 12

Slide 12 text

def a_function(*args, **kwargs): return 'Hello DjangoCon 2015!' >>> a_function() 'Hello DjangoCon 2015!'

Slide 13

Slide 13 text

>>> lambda_function = lambda: 'Enjoying Austin?' >>> lambda_function() 'Enjoying Austin?'

Slide 14

Slide 14 text

class FirstClass: an_attribute = ( 'Have you visited any good restaurants?') def a_method(*args, **kwargs): self = args[0] return self.an_attribute >>> fc_obj = FirstClass() >>> fc_obj.a_method() 'Have you visited any good restaurants?'

Slide 15

Slide 15 text

class SecondClass(FirstClass): def __init__(self): """Magic method to initialize a class""" self.an_attribute = ( "Easy Tiger, La Condessa and " "Lambert's are my favorites.") >>> sc_obj = SecondClass() >>> sc_obj.a_method() "Easy Tiger, La Condessa and Lambert's are my favorites."

Slide 16

Slide 16 text

class ThirdClass(SecondClass): def __call__(*args, **kwargs): """Magic method to make object callable""" return ( "I like grabbing ice cream at " "Amy's, too.") >>> tc_obj = ThirdClass() >>> tc_obj() "I like grabbing ice cream at Amy's, too."

Slide 17

Slide 17 text

>>> callable(a_function) True >>> callable(lambda_function) True >>> callable(FirstClass) True >>> callable(fc_obj) False >>> callable(sc_obj) False >>> callable(tc_obj) True

Slide 18

Slide 18 text

WHAT IS HTTP, ANYWAY? UNDERSTANDING THE PROBLEM

Slide 19

Slide 19 text

HyperText Transfer Protocol Defines a client and server how to communicate HTTP Request Methods HTTP Response Codes Safe Methods and Idempotent Methods

Slide 20

Slide 20 text

HyperText Transfer Protocol Methods GET HEAD OPTIONS POST PUT Codes 200 400 403 404 500

Slide 21

Slide 21 text

HyperText Transfer Protocol Idempotent Methods POST PUT

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

Your website must adhere to HTTP

Slide 24

Slide 24 text

Andrew’s Server Request Methods GIMME HAVE Response Code CANHAS NOPE

Slide 25

Slide 25 text

Your website must adhere to HTTP

Slide 26

Slide 26 text

Goal of Software Solve a Problem Automate Behavior

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

Goal of Software Solve a Problem Automate Behavior

Slide 29

Slide 29 text

HTTP is the problem web frameworks solve You are the behavior frameworks automate

Slide 30

Slide 30 text

DJANGO’S REQUEST/RESPONSE CYCLE UNDERSTANDING THE PROBLEM

Slide 31

Slide 31 text

What is a view? 'A view is a "type" of Web page' "views are for displaying content" (DORK-1) Dynamic generation of content

Slide 32

Slide 32 text

Step 3. HTTP Response Step 1. HTTP Request Website Step 2. Computation

Slide 33

Slide 33 text

Database Views URL Dispatch URL Patterns Template Loader Template Files Models Forms Context Processors

Slide 34

Slide 34 text

Simplification No WSGI Server No View Middleware No Exception Handling

Slide 35

Slide 35 text

Views URL Dispatch URL Patterns

Slide 36

Slide 36 text

Views URL Patterns METHOD /path/to/resource/ HTTP/1.1

Slide 37

Slide 37 text

Views URL Patterns METHOD /path/to/resource/ HTTP/1.1 METHOD /path/to/resource/ HTTP/1.1

Slide 38

Slide 38 text

Views URL Patterns METHOD /path/to/resource/ HTTP/1.1 METHOD /path/to/resource/ HTTP/1.1

Slide 39

Slide 39 text

What is a view? Accept HttpRequest object Generate data based on: HTTP request method Request data (POST, PUT, etc) Data from dispatch (from the URL path) Return HttpResponse object

Slide 40

Slide 40 text

What is a view? Any Python Callable

Slide 41

Slide 41 text

Why do we talk about functions and classes (and generics)?

Slide 42

Slide 42 text

A BRIEF HISTORY OF VIEWS FROM WHEN DINOSAURS STILL ROAMED THE EARTH UNTIL THE ROBOT APOCALYPSE

Slide 43

Slide 43 text

A Brief History of Views July 2005: Django Function views in original tarball July 2005: Generic views in SVN revision 304

Slide 44

Slide 44 text

Functions are Rigid Extend generic views? Use classes!

Slide 45

Slide 45 text

The big win from a class-based view is [...] being able to override parts of the behavior without needing to rewrite the entire view, or add 101 parameters. –Alex Gaynor https://groups.google.com/d/msg/django-developers/J87Hm3hO9z8/gWunEs9QwMwJ

Slide 46

Slide 46 text

A Brief History of Views July 2005: Django Function views in original tarball July 2005: Generic views in SVN revision 304 March 2008: Joseph Kocherhans #6735

Slide 47

Slide 47 text

Class-Based Views Simple (Usable - principle of least surprise) Extendable Inheritance Decorators Safe (Thread-Safe) Testable

Slide 48

Slide 48 text

A Brief History of Views July 2005: Django Function views in original tarball July 2005: Generic views in SVN revision 304 March 2008: Joseph Kocherhans #6735 March 2011: (G)CBV Released in Django 1.3

Slide 49

Slide 49 text

The Naming Problem Generic Views Class-Based Views (CBV) Class-Based + Generic Views (CBGV)

Slide 50

Slide 50 text

The Naming Problem Object Views Generic (Class-Based) Views (GCBV)

Slide 51

Slide 51 text

State of the Pony Function Views Object Views (Class-Based Views) Generic (Class-Based) Views

Slide 52

Slide 52 text

FUNCTION VIEWS HOW I LEARNED TO STOP WORRYING AND LOVE NON-COMPLIANCE

Slide 53

Slide 53 text

class ExampleModel(models.Model): name = models.CharField(max_length=31) slug = models.SlugField(max_length=31) def __str__(self): return self.name.title()

Slide 54

Slide 54 text

from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P[\w\-]+)/$', views.model_detail, name='model_detail'), ]

Slide 55

Slide 55 text

from django.shortcuts import ( get_object_or_404, render) from .models import ExampleModel def model_detail(request, *args, **kwargs): request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj})

Slide 56

Slide 56 text

Database Views URL Dispatch URL Patterns Template Loader Template Files Models Forms Context Processors

Slide 57

Slide 57 text

from django.shortcuts import ( get_object_or_404, render) from .models import ExampleModel def model_detail(request, *args, **kwargs): request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj})

Slide 58

Slide 58 text

Views URL Patterns METHOD /path/to/resource/ HTTP/1.1 METHOD /path/to/resource/ HTTP/1.1

Slide 59

Slide 59 text

from django.http import HttpResponseNotAllowed def model_detail(request, *args, **kwargs): if request.method == 'GET': request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj}) return HttpResponseNotAllowed(['GET'])

Slide 60

Slide 60 text

from django.views.decorators.http import \ require_http_methods @require_http_methods(['GET', 'HEAD']) def model_detail(request, *args, **kwargs): request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj})

Slide 61

Slide 61 text

@require_http_methods(['GET', 'HEAD']) def model_detail(request, *args, **kwargs): ... ‑ @require_safe def model_detail(request, *args, **kwargs): ...

Slide 62

Slide 62 text

$ ./manage.py runserver $ telnet localhost 8000

Slide 63

Slide 63 text

GET /django/ HTTP/1.1 HTTP/1.0 200 OK Date: Wed, 26 Aug 2015 17:38:38 GMT Server: WSGIServer/0.2 CPython/3.4.3 Content-Type: text/html; charset=utf-8 X-Frame-Options: SAMEORIGIN

Slide 64

Slide 64 text

OPTIONS /django/ HTTP/1.1 HTTP/1.0 405 METHOD NOT ALLOWED Date: Wed, 26 Aug 2015 17:43:44 GMT Server: WSGIServer/0.2 CPython/3.4.3 Allow: GET, HEAD Content-Type: text/html; charset=utf-8 X-Frame-Options: SAMEORIGIN

Slide 65

Slide 65 text

POST /django/ HTTP/1.1 HTTP/1.0 403 FORBIDDEN Date: Wed, 26 Aug 2015 17:41:45 GMT Server: WSGIServer/0.2 CPython/3.4.3 Content-Type: text/html X-Frame-Options: SAMEORIGIN

Slide 66

Slide 66 text

url(r'^create/$', views.model_create, name='model_create'),

Slide 67

Slide 67 text

def model_create(request, *args, **kwargs): if request.method == 'POST': form = ExampleForm(request.POST) if form.is_valid(): new_obj = form.save() return redirect(new_obj) else: form = ExampleForm() return render( request, 'viewsapp/form.html', {'form': form})

Slide 68

Slide 68 text

No content

Slide 69

Slide 69 text

@require_http_methods(['GET', 'HEAD', 'POST']) def model_create(request, *args, **kwargs): ...

Slide 70

Slide 70 text

CLASS-BASED VIEWS AS DRY AS THE SAHARA

Slide 71

Slide 71 text

url(r'^(?P[\w\-]+)/$', views.ModelDetail.as_view(), name='model_detail'),

Slide 72

Slide 72 text

@require_safe def model_detail(request, *args, **kwargs): request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj})

Slide 73

Slide 73 text

def model_detail(request, *args, **kwargs): request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj})

Slide 74

Slide 74 text

def get(self, request, *args, **kwargs): request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj})

Slide 75

Slide 75 text

class ModelDetail(View): def get(self, request, *args, **kwargs): request_slug = kwargs.get('slug') example_obj = get_object_or_404( ExampleModel, slug=request_slug) return render( request, 'viewsapp/detail.html', {'object': example_obj})

Slide 76

Slide 76 text

OPTIONS /django/ HTTP/1.1 HTTP/1.0 200 OK Date: Wed, 26 Aug 2015 17:48:24 GMT Server: WSGIServer/0.2 CPython/3.4.3 Allow: GET, HEAD, OPTIONS X-Frame-Options: SAMEORIGIN Content-Type: text/html; charset=utf-8 Content-Length: 0

Slide 77

Slide 77 text

url(r'^create/$', views.ModelCreate.as_view(), name='model_create'),

Slide 78

Slide 78 text

class ModelCreate(View): context_object_name = 'form' form_class = ExampleForm template_name = 'viewsapp/form.html' def get(self, request, *args, **kwargs): ... def post(self, request, *args, **kwargs): ...

Slide 79

Slide 79 text

class ModelCreate(View): def get(self, request, *args, **kwargs): return render( request, self.template_name, {self.context_object_name: self.form_class()})

Slide 80

Slide 80 text

class ModelCreate(View): def post(self, request, *args, **kwargs): bound_form = self.form_class(request.POST) if bound_form.is_valid(): new_obj = bound_form.save() return redirect(new_obj) return render( request, self.template_name, {self.context_object_name: bound_form})

Slide 81

Slide 81 text

@require_http_methods(['GET', 'HEAD', 'POST']) def model_create(request, *args, **kwargs): if request.method == 'POST': form = ExampleForm(request.POST) if form.is_valid(): new_obj = form.save() return redirect(new_obj) else: form = ExampleForm() return render( request, 'viewsapp/form.html', {'form': form})

Slide 82

Slide 82 text

class ModelCreate(View): def get(self, request, *args, **kwargs): # show form def post(self, request, *args, **kwargs): # show form if error # use data if valid

Slide 83

Slide 83 text

GENERIC CLASS-BASED VIEWS OH FOR THE LOVE OF GRAPH THEORY

Slide 84

Slide 84 text

from django.views.generic import DetailView, View class ModelDetail(DetailView): model = ExampleModel template_name = 'viewsapp/detail.html'

Slide 85

Slide 85 text

from django.views.generic import ( CreateView, DetailView) class ModelCreate(CreateView): context_object_name = 'form' form_class = ExampleForm template_name = 'viewsapp/form.html'

Slide 86

Slide 86 text

The Problem put(*args, **kwargs) The PUT action is also handled and just passes all parameters through to post(). https://docs.djangoproject.com/en/1.8/ref/class-based-views/mixins-editing/ #django.views.generic.edit.ProcessFormView.put

Slide 87

Slide 87 text

No content

Slide 88

Slide 88 text

No content

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

https://ccbv.co.uk

Slide 93

Slide 93 text

Stick to the basics display a list of objects display a single object create a single object update a single object delete a single object

Slide 94

Slide 94 text

No content

Slide 95

Slide 95 text

ENHANCE! MAKING VIEWS EASIER

Slide 96

Slide 96 text

Classy Class Based Views http://ccbv.co.uk

Slide 97

Slide 97 text

No content

Slide 98

Slide 98 text

No content

Slide 99

Slide 99 text

No content

Slide 100

Slide 100 text

No content

Slide 101

Slide 101 text

No content

Slide 102

Slide 102 text

django-decorator-plus

Slide 103

Slide 103 text

from decorator_plus import ( require_form_methods, require_safe_methods) @require_safe_methods def model_detail(request, *args, **kwargs): ... @require_form_methods def model_create(request, *args, **kwargs): ...

Slide 104

Slide 104 text

from decorator_plus import require_http_methods @require_http_methods(['GET']) def model_detail(request, *args, **kwargs): ... @require_http_methods(['GET', 'POST']) def model_create(request, *args, **kwargs): ...

Slide 105

Slide 105 text

@require_safe_methods @require_http_methods(['GET']) @require_form_methods @require_http_methods(['GET', 'POST']) HEAD && OPTIONS Included

Slide 106

Slide 106 text

IN CONCLUSION ONE SIZE FITS NO-ONE

Slide 107

Slide 107 text

Answers: Django handles HTTP for me! Why do I have to worry about it? When is Django deprecating function views? Aren’t all class-based views generic? How do I choose what kind of view to use?

Slide 108

Slide 108 text

The Questions Does a generic view do what I want (or almost)? If so, use a generic (and https://ccbv.co.uk). Do I need to inherit/share behavior with another view? If so, use a CBV. If not, then it doesn’t matter.

Slide 109

Slide 109 text

Key Take-Aways The view is Django’s solution to HTTP methods All views are callables require_http_methods() should be used with function views Generic Class-Based Views (GCBV) are pre- programmed Class-Based Views (CBV), and are separate concepts with different uses

Slide 110

Slide 110 text

Thank you! Related Materials: afrg.co/views Django Unleashed: afrg.com/dju Django Class: afrg.co/class @andrewsforge