Django..

First steps

What is Framework?

Application or set of modules
Goal: Agile application development

About Frameworks.. 

Framework / No framework

  • 2005 realased BSD
  • 2008 Django software foundation

Django

  • Django is a high-level Python Web framework that encourages rapid development and clean

  • It’s free and open source

Also...

Ridiculously fast

Fully loaded

Secure

Scalable

Versatile

Companies using Django

Disqus

Mozilla

Pinterest

Mozilla

National Geographic

Instagram

Open Stack

MacArthur Foundation

Open Knowledge Foundation

 

Django Architecture

  1. Models

  2. Templates

  3. Views

Models

Models provide the business logic and state to an application

i.e. models are a form of data abstraction which separate out the state of data and the methods for manipulating that data from the rest of the application

Django does this via an Object Relational Mapper (ORM) which maps Python Classes to physical data stores most commonly SQL databases

Example

# Modelo persona
class Persona(models.Model):
    usuario = models.OneToOneField(User, on_delete=models.CASCADE)
    fecha_nacimiento = models.DateField(auto_now_add=False)
    direccion = models.CharField(max_length=50)
    sexo = models.CharField(max_length=10)
    fecha_creacion = models.DateTimeField(auto_now_add=True)
    ciudad = models.ForeignKey(Ciudad, on_delete=models.CASCADE)

    class Meta:
        verbose_name_plural = "personas"

    def __unicode__(self):
        return str(self.usuario)

    def __str__(self):
        return str(self.usuario)
# Generar migracion
./manage.py makemigrations


# Aplicar migración
./manage.py migrate
CREATE TABLE `navidad_persona` (
	`id`	integer NOT NULL PRIMARY KEY AUTOINCREMENT,
	`fecha_nacimiento`	date NOT NULL,
	`direccion`	varchar ( 50 ) NOT NULL,
	`sexo`	varchar ( 10 ) NOT NULL,
	`fecha_creacion`	datetime NOT NULL,
	`ciudad_id`	integer NOT NULL,
	`usuario_id`	integer NOT NULL UNIQUE,
	FOREIGN KEY(`ciudad_id`) 
            REFERENCES `navidad_ciudad`(`id_ciudad`) DEFERRABLE INITIALLY DEFERRED,
	FOREIGN KEY(`usuario_id`) 
            REFERENCES `auth_user`(`id`) DEFERRABLE INITIALLY DEFERRED
);
                       #Querys Django

Persona.objects.all()        

SELECT * FROM navidad_persona;

Persona.objects.filter(user__username='jamarin90')

SELECT username FROM auth_user, navidad_persona
WHERE auth_user=username and auth_user='jamarin90'

Templates

Templates provide the physical appearence of the current state of the data

i.e. templates have knowledge of the data format and can show its current state in a human readable way

In Django this is done by a simplistic templating language embedded within normal HTML code, with lots of convenience functions for displaying output

Example

My first name is {{ first_name }}. My last name is {{ last_name }}


# Tags
{% csrf_token %}

# Ex:
{'django': 'the web framework for perfectionists with deadlines'}

{{ django|title }}

Result: 

The Web Framework For Perfectionists With Deadlines


{{ my_date|date:"Y-m-d" }}
<html>
  <head>
    <title>Band Listing</title>
  </head>
  <body>
    <h1>All Bands</h1>
    <ul>
    {% for band in bands %}
      <li>
        <h2><a href="{{ band.get_absolute_url }}">{{ band.name }}</a></h2>
        {% if band.can_rock %}<p>This band can rock!</p>{% endif %}
      </li>
    {% endfor %}
    </ul>
  </body>
</html>

Views

Views bring everything else together

 

Views are the segments of code which connect the requests to the data, and then sends data back to the user interface

Views take in HTTP requests, interact with the models and then pass the models onto the templates

Example

from django.shortcuts import render

def band_listing(request):
    """A view of all bands."""
    bands = models.Band.objects.all()
    return render(request, 'bands/band_listing.html', {'bands': bands})
from django.http import HttpResponse

def home(request):
    return HttpResponse('Hello, World!')

Mapping

We now have a basis for requests coming in, being passed onto a view, manipulating models and sending them to the template to create a userinterface

 

What you might be asking yourself now is, how does Django know what view to send a particular request?

Django uses a mapping file called urls.py which maps html addresses to views, using regular expressions

Example

from django.urls import path

from . import views

urlpatterns = [
    path('bands/', views.band_listing, name='band-list'),
    path('bands/<int:band_id>/', views.band_detail, name='band-detail'),
    path('bands/search/', views.band_search, name='band-search'),
]
from django.conf.urls import url
from django.contrib import admin

from boards import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^admin/', admin.site.urls),
]

Thank You!!