Getting started with Django
Camilo Nova
Don't know who am I?
- Open Source Developer
- Django Developer Member
- Early stage investor
- Django Bogota Founder
- AxiaCore CEO
You don't believe?
github.com/camilonova
Ridiculously fast.
Seriously secure.
Exceedingly scalable.
models.py
from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
def __str__(self): # __unicode__ on Python 2
return self.full_name
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter)
def __str__(self): # __unicode__ on Python 2
return self.headline
models API
# Import the models we created from our "news" app
>>> from news.models import Reporter, Article
# No reporters are in the system yet.
>>> Reporter.objects.all()
[]
# Create a new Reporter.
>>> r = Reporter(full_name='John Smith')
# Save the object into the database. You have to call save() explicitly.
>>> r.save()
# Now it has an ID.
>>> r.id
1
# Now the new reporter is in the database.
>>> Reporter.objects.all()
[<Reporter: John Smith>]
models API
# Fields are represented as attributes on the Python object.
>>> r.full_name
'John Smith'
# Django provides a rich database lookup API.
>>> Reporter.objects.get(id=1)
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__startswith='John')
<Reporter: John Smith>
>>> Reporter.objects.get(full_name__contains='mith')
<Reporter: John Smith>
>>> Reporter.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Reporter matching query does not exist.
# Create an article.
>>> from datetime import date
>>> a = Article(pub_date=date.today(), headline='Django is cool',
... content='Yeah.', reporter=r)
>>> a.save()
# Now the article is in the database.
>>> Article.objects.all()
[<Article: Django is cool>]
models API
# Article objects get API access to related Reporter objects.
>>> r = a.reporter
>>> r.full_name
'John Smith'
# And vice versa: Reporter objects get API access to Article objects.
>>> r.article_set.all()
[<Article: Django is cool>]
# The API follows relationships as far as you need, performing efficient
# JOINs for you behind the scenes.
# This finds all articles by a reporter whose name starts with "John".
>>> Article.objects.filter(reporter__full_name__startswith='John')
[<Article: Django is cool>]
# Change an object by altering its attributes and calling save().
>>> r.full_name = 'Billy Goat'
>>> r.save()
# Delete an object with delete().
>>> r.delete()
admin.py
from django.contrib import admin
from . import models
admin.site.register(models.Article)
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^articles/([0-9]{4})/$', views.year_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]
views.py
from django.shortcuts import render
from .models import Article
def year_archive(request, year):
a_list = Article.objects.filter(pub_date__year=year)
context = {'year': year, 'article_list': a_list}
return render(request, 'news/year_archive.html', context)
template.html
{% extends "base.html" %}
{% block title %}Articles for {{ year }}{% endblock %}
{% block content %}
<h1>Articles for {{ year }}</h1>
{% for article in article_list %}
<p>{{ article.headline }}</p>
<p>By {{ article.reporter.full_name }}</p>
<p>Published {{ article.pub_date|date:"F j, Y" }}</p>
{% endfor %}
{% endblock %}
base.html
{% load staticfiles %}
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<img src="{% static "images/sitelogo.png" %}" alt="Logo" />
{% block content %}{% endblock %}
</body>
</html>
Installing Django
$ easy_install pip
...
$ pip install virtualenv
...
$ virtualenv miproyecto_env
New python executable in miproyecto_env/bin/python
Installing setuptools, pip, wheel...done.
$ cd miproyecto_env
$ source bin/activate
(miproyecto_env)$ pip install django
Collecting django
Downloading Django-1.8.7-py2.py3-none-any.whl (6.2MB)
100% |████████████████████████████████| 6.2MB 82kB/s
Installing collected packages: django
Successfully installed django-1.8.7
(miproyecto_env)$ django-admin startproject miproyecto
File Structure
miproyecto/
manage.py
miproyecto/
__init__.py
settings.py
urls.py
wsgi.py
Database setup
(miproyecto_env)$ cd miproyecto
(miproyecto_env)$ python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, contenttypes, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying sessions.0001_initial... OK
Run Server
(miproyecto_env)$ python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
November 28, 2015 - 18:17:17
Django version 1.8.7, using settings 'miproyecto.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Get involved
django-axes
https://github.com/django-pci/django-axes
django-extensions
github.com/django-extensions/django-extensions
Build
Something
Amazing
Share the 💖
or ask me anything...
Getting started with django
By Camilo Nova
Getting started with django
- 1,687