Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Django

Sidnet
January 28, 2016

 Django

Created and presented by Paweł Adamczak.

Sidnet

January 28, 2016
Tweet

More Decks by Sidnet

Other Decks in Programming

Transcript

  1. 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)
  2. 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).
  3. 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
  4. 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)
  5. 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'
  6. Quentin Tarantino - witty dialogue - distinctive use of music

    - non-linear narratives - use of graphic violence - love of 70mm
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. >>> Employee.objects.create(name='Bender Rodríguez', role='BENDING') <Employee: Bender Rodríguez> >>> 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.
  12. 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.
  13. 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.
  14. >>> 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!")
  15. 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, )
  16. 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)
  17. Forms And are versatile. # In template … <form method="post">

    {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> Forms also have built in rendering. {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help"> {{ field.help_text|safe }} </p> {% endif %} </div> {% endfor %}
  18. 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__'
  19. 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
  20. 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.
  21. 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)
  22. 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)
  23. 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
  24. 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
  25. 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')
  26. 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')
  27. 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)
  28. 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
  29. 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
  30. 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.
  31. 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
  32. 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.
  33. Fin

  34. Sources - IMDB - http://www.imdb.com - Wikipedia - https://wikipedia.org -

    Django Documentation - https://docs.djangoproject.com