Slide 1

Slide 1 text

Django by Paweł Adamczak January 28, 2016

Slide 2

Slide 2 text

Django Unchained (2012) Director: Quentin Tarantino Starring: Jamie Foxx, Christoph Waltz, Leonardo DiCaprio, Kerry Washington, and Samuel L. Jackson Recognition: 38 nominations and 15 awards (2 Oscars and Golden Globes)

Slide 3

Slide 3 text

Django Unchained (2012) The story is set in the Deep South in the early winter of 1858 and the following spring of 1859, two years before the outbreak of the American Civil War. With the help of a German bounty hunter (Waltz), a freed slave (Foxx) sets out to rescue his wife from a brutal Mississippi plantation owner (DiCaprio).

Slide 4

Slide 4 text

Django (1966) Director: Sergio Corbucci Starring: Franco Nero, Loredana Nusciak, José Bodalo - considered as being one of the most violent films ever made - Tarantino’s Django Unchained is a homage to this classic spaghetti western

Slide 5

Slide 5 text

Quentin Tarantino

Slide 6

Slide 6 text

Quentin Tarantino Born: March 27, 1963 (age 52) Movies: Reservoir Dogs (1992), Pulp Fiction (1994), Jackie Brown (1997), Kill Bill (2003 & 2004), Grindhouse: Death Proof (2007), Inglourious Basterds (2009), Django Unchained (2012), The Hateful Eight (2015) Recognition: 45 nominations and 28 awards (2 Oscars and Golden Globes)

Slide 7

Slide 7 text

Quentin Tarantino - Dropped out of high school, but found a job as a clerk at Video Archives in Manhattan Beach. - Made his way in the industry by writing the screenplay to 'True Romance' and 'Natural Born Killers'

Slide 8

Slide 8 text

Quentin Tarantino - witty dialogue - distinctive use of music - non-linear narratives - use of graphic violence - love of 70mm

Slide 9

Slide 9 text

But also:

Slide 10

Slide 10 text

Django Web Framework - Free and open source web application framework, written in Python. - Born in 2003, when programmers at the Lawrence Journal-World newspaper began using Python to build its website. It was released publicly in 2005.

Slide 11

Slide 11 text

Django Web Framework - Its motto: ‘The web framework for perfectionists with deadlines’. - Some popular sites that use Django: Pinterest, Instagram, Mozilla, Disqus, Bitbucket, Pitchfork, National Geographic.

Slide 12

Slide 12 text

First, some basics

Slide 13

Slide 13 text

class Employee(models.Model): name = models.CharField(max_length=128) ROLE_CHOICES = ( ('PIZZA', 'pizza delivery boy'), ('PILOT', 'spaceship pilot'), ('BENDING', 'bending unit'), ('DOCTOR', 'doctor'), ) role = models.CharField(max_length=16, choices=ROLE_CHOICES) def __str__(self): return self.name Models Models are Python classes that extend models.Model. Every field is an instance of models.Field type object. You can also create your own fields.

Slide 14

Slide 14 text

class Employee(models.Model): name = models.CharField(max_length=128) ROLE_CHOICES = ( ('PIZZA', 'pizza delivery boy'), ('PILOT', 'spaceship pilot'), ('BENDING', 'bending unit'), ('DOCTOR', 'doctor'), ) role = models.CharField(max_length=16, choices=ROLE_CHOICES) def __str__(self): return self.name Models Sample field types: ForeignKey, FileField, DateField, SlugField, ManyToManyField, etc. Sample field options: default, choices, unique, help_text, editable, etc.

Slide 15

Slide 15 text

>>> Employee.objects.create(name='Bender Rodríguez', role='BENDING') >>> Employee.objects.bulk_create([ Employee(name='Philip J. Fry', role='PIZZA'), Employee(name='Turanga Leela', role='PILOT'), ]) >>> Employee.objects.filter( role='DOCTOR').exists() False ORM ORM is straightforward and easy to use. Sample methods: create, bulk_create, exists, filter, latest, values, dates, etc.

Slide 16

Slide 16 text

Now, some of the features that I consider mention worthy

Slide 17

Slide 17 text

manage.py@planet-express > makemigrations Migrations for 'employees': 0001_initial.py: - Create model Employee manage.py@planet-express > migrate Running migrations: Rendering model states... DONE Applying employees.0001_initial... OK Migrations Migrations are done automatically and incrementally, with every change applied to application models.

Slide 18

Slide 18 text

Database backends Models and database backend are separated, fully interchangeable and can be changed with one setting. As usual - you can also create your own backend.

Slide 19

Slide 19 text

>>> zoidberg = Employee(name='John A. Zoidberg', role='PILOT') >>> zoidberg.full_clean() Traceback (most recent call last): ... django.core.exceptions.ValidationError: {'__all__': ['Whoop, whoop, whoop!']} Model validation Model validation is extremely easy and can be used to check and inspect the data throughout the application, whether you create objects from code, shell or forms. # In models ... def clean(self): if ('Zoidberg' in self.name and self.role != 'DOCTOR'): raise ValidationError( "Whoop, whoop, whoop!")

Slide 20

Slide 20 text

Forms

Slide 21

Slide 21 text

Forms Forms are the most popular way to collect data from users, so Django made it easy to create and manage them from within the application. class PlanetExpressContactForm(forms.Form): subject = forms.CharField( max_length=100, ) message = forms.CharField( widget=forms.Textarea, ) sender = forms.EmailField() cc_myself = forms.BooleanField( required=False, )

Slide 22

Slide 22 text

Forms are the most popular way to collect data from users, so Django made it easy to create and manage them from within the application. Forms # In view … if form.is_valid(): data = form.cleaned_data subject = data['subject'] message = data['message'] sender = data['sender'] cc_myself = data['cc_myself'] recipients = ['[email protected]'] if cc_myself: recipients.append(sender) send_mail(subject, message, sender, recipients)

Slide 23

Slide 23 text

Forms And are versatile. # In template … {% csrf_token %} {{ form }} Forms also have built in rendering. {% for field in form %}
{{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %}

{{ field.help_text|safe }}

{% endif %}
{% endfor %}

Slide 24

Slide 24 text

class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = ['name', 'role'] widgets = { 'role': forms.RadioSelect, } Model Forms Model forms automatically create a form for provided model, with its data validation and default widgets. class EmployeeForm(forms.ModelForm): class Meta: model = Employee fields = '__all__'

Slide 25

Slide 25 text

Views

Slide 26

Slide 26 text

Wait, why are ‘controllers’ called ‘views’? Django’s View: - describes which data you see, not how you see it - separates content from presentation MVC’s controller: - translates interactions with the view into actions to be performed by the model

Slide 27

Slide 27 text

Wait, why are ‘controllers’ called ‘views’? The way Django developers see it, both Django’s view and template can be considered as the ‘view’ part in MVC and ‘controller’ is actually Django itself.

Slide 28

Slide 28 text

Django’s views are simple Python functions that take request and return an HttpResponse (here via helper render() function). Views def employees_list_view(request): template_name = 'employees/list.html' ctx = dict() # Employees ctx['employees'] = Employee.objects.all() return render(request, template_name, ctx)

Slide 29

Slide 29 text

Django’s views are simple Python functions that take request and return HttpRequest type object (here via helper render() function). Views def employees_form_view(request): template_name = 'employees/form.html' ctx = dict() # Form form = EmployeeForm( data=request.POST or None) ctx['form'] = form if form.is_valid(): form.save() return render(request, template_name, ctx)

Slide 30

Slide 30 text

Class-based views were introduced as alternative, more DRY and flexible approach to classic function-based views. Class Based Views class EmployeesListView(TemplateView): template_name = 'employees/list.html' def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) # Employees ctx['employees'] = Employee.objects.all() return ctx

Slide 31

Slide 31 text

But generic class-based views are the real deal. They allow you to do the most common scenarios in couple lines of code, nice and easy. Class Based Views def employees_list_view(request): template_name = 'employees/list.html' ctx = dict() # Employees ctx['employees'] = Employee.objects.all() return render(request, template_name, ctx) class EmployeesListView(ListView): template_name = 'employees/list.html' model = Employee

Slide 32

Slide 32 text

Form views are even better. Class Based Views def employees_form_view(request): template_name = 'employees/form.html' ctx = dict() # Form form = EmployeeForm( data=request.POST or None) ctx['form'] = form if form.is_valid(): form.save() return render(request, template_name, ctx) class EmployeesFormView(FormView): template_name = 'employees/form.html' form_class = EmployeeForm success_url = reverse('index')

Slide 33

Slide 33 text

As a matter of fact, the whole CRUD can be done in 40 lines of code. Class Based Views class EmployeeUpdateView(UpdateView): template_name = 'employee/create.html' model = Employee fields = '__all__' success_url = reverse('index') class EmployeeDeleteView(DeleteView): template_name = 'employee/delete.html' model = Employee success_url = reverse('index') class EmployeeCreateView(CreateView): template_name = 'employee/create.html' model = Employee fields = '__all__' success_url = reverse('index')

Slide 34

Slide 34 text

As important, everything in CBV is put inside methods which are extendable and very easy to modify. Class Based Views class UserProfileView(DetailView): template_name = 'user/profile.html' model = User def get_object(queryset=None): return self.request.user def get_context_data(self, **kwargs): role = self.request.user.role kwargs['employees'] = Employee. objects.filter(role=role) return super().get_context_data( **kwargs)

Slide 35

Slide 35 text

Filtering? Done. Pagination? Just add one variable. Do something after form submission? Just extend form_valid(). Class Based Views class ZoidbergEmployeesListView(ListView): template_name = 'employees/list.html' model = Employee paginate_by = 10 def get_queryset(): qs = super().get_queryset() return qs.filter( name__icontains='Zoidberg') def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx['title'] = 'Whoop, whoop, whoop!' return ctx

Slide 36

Slide 36 text

And last, but definitely not least - you can also inherit from Mixins, which are classes that usually add one, extra functionality (the hint is usually in the name). Class Based Views class EmployeesListView(UserPassesTestMixin, ListView): template_name = 'employees/list.html' model = Employee def test_func(self): user = self.request.user return user.email.endswith( '@pythonity.com') class EmployeesListView(LoginRequiredMixin, ListView): template_name = 'employees/list.html' model = Employee

Slide 37

Slide 37 text

And finally, some other stuff

Slide 38

Slide 38 text

Django Authentication - Django also has builtin User, Group and Permission models - All basic forms and views - such as password_reset, UserCreationForm, etc. - are already implemented. - Every model has add, change and delete permission by default.

Slide 39

Slide 39 text

Django Admin is a builtin administration panel from which you can see your data and manage it. It’s not really flexible, but it’s there and it’s helpful. Django Admin

Slide 40

Slide 40 text

Remember our model form and model validation? Django Admin

Slide 41

Slide 41 text

manage.py manage.py is Django’s command-line utility for performing administrative tasks. Yes, you can also easily add your own. Sample commands: startproject, createsuperuser, runserver, dumpdata, loaddata, makemessages, collectstatic, migrate, makemigrations, etc.

Slide 42

Slide 42 text

Fin

Slide 43

Slide 43 text

Sources - IMDB - http://www.imdb.com - Wikipedia - https://wikipedia.org - Django Documentation - https://docs.djangoproject.com

Slide 44

Slide 44 text

Thanks