Your SlideShare is downloading. ×
0
Introduction to Django   Master in Free Software 2012, July 14 2012     Joaquim Rocha <jrocha@igalia.com>
What is it?"Django is a highlevel Python Web frameworkthat encourages rapid development andclean, pragmatic design."(from ...
What is it?Created by Lawrence Journal-World en 2003Should help journalists meet hard deadlinesShould not stand in the way...
The frameworkObject-Relational Mapper (ORM)Automatic admin interfaceElegant URL designPowerful templating systemi18n
Big communityDjango has a big community and an extense list of appsSearch for them in http://github.com, http://code.googl...
Production EnvironmentNginx + Gunicornmod_wsgiFastCGImod_python...
DB BackendOfficially supported:PostreSQLMySQLSQLiteOracle
Using Django
Development EnvironmentDownload it and install Django from http://djangoproject.com/download orBe smart and use Pythons Vi...
VirtualEnvA self-contained virtual environment for Python developmentAdvantages:* Does not touch your Python installation*...
Install VirtualEnv and DjangoInstall VirtualEnv:# apt-get install python-virtualenvCreate a virtual environment:$ virtuale...
Development
Creating a project$ django-admin.py startproject myprojectmyproject/ manage.py myproject/  __init__.py  settings.py  urls....
Running a project$ ./manage.py runserver... and open in your browser: localhost:8000
DevelopmentDjango projects are composed by appsapps are the projects modules
Creating an applicationInside a project, do:$ python manage.py startapp my_appmy_app/ __init__.py models.py tests.py views...
Build the DB$ python manage.py syncdb
Project configurationEasy configuration in file settings.py
DevelopmentDjango follows the MTV design patternModel-Template-View
ModelsModels are classes that represent objectsin the databaseAnd youll never have to touch SQL again!
Modelsmodels.py:class Post(models.Model):    title = models.CharField(max_length = 500)    content = models.TextField()   ...
ViewsViews are functions that usually processmodels and render HTMLIts where the magic happens!How to get all posts from t...
Viewviews.py:import datetimefrom models import Postdef view_latest_posts(request):    # Last 5 days    date = datetime.dat...
TemplatesThey will help you not repeating yourself!And designers wont have to touch code:
base.html:<html>    <head>        <title>{% block title %}{% endblock %}</title>    </head>    <body>        {% block cont...
home.html:{% extends "base.html" %}{% block title %}Homepage{% endblock %}{% block content %}    <h3>This will be some mai...
URLsIn Django, URLs are part of the design!urls.py use regular expressions to map URLs with views
URLsurls.py:from django.conf.urls import patterns, include, urlurlpatterns = patterns(Project.some_app.views,  url(r^$, in...
Class-based ViewsAllow to structure views and reuse code.They are also faster to use, for common tasks like listingor show...
FormsClasses that represent HTML formsThey allow to easily configure theexpected type of inputs, error messages, labels, etc.
Formsforms.py:class CreatePost(forms.Form):    title = forms.CharField(label="Post Title",                  max_length=500...
Formsviews.py:def create_post(request):    if request.method == POST:        form = CreatePost(request.POST)        if for...
Formscreate_post.html:<form action="/create/" method="POST">    {% csrf_token %}    {{ form.as_p }}    <input type="submit...
Forms for ModelsForms that are created automatically for modelos, just like:from django.forms import modelsclass PostForm(...
Automatic AdminTo enable automatic admin, follow the instructionsin your projects URLs (uncomment the admin URLs)and uncom...
This gives you automatic login...
... and creation, edition, deletion of objects
Next steps
Django friendly hostsAn extense list can be found at:http://code.djangoproject.com/wiki/DjangoFriendlyWebHostsGoogle AppEn...
HelpDjango Documentation:https://docs.djangoproject.comCheat sheet:http://www.revsys.com/django/cheatsheet/Some books:The ...
Upcoming SlideShare
Loading in...5
×

Introduction to Django

1,982

Published on

An introduction to Django for the Master in Free Software by Igalia covering basic usage and updated to Django 1.4.

0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,982
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
57
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "Introduction to Django"

  1. 1. Introduction to Django Master in Free Software 2012, July 14 2012 Joaquim Rocha <jrocha@igalia.com>
  2. 2. What is it?"Django is a highlevel Python Web frameworkthat encourages rapid development andclean, pragmatic design."(from Djangos official webpage)
  3. 3. What is it?Created by Lawrence Journal-World en 2003Should help journalists meet hard deadlinesShould not stand in the way of journalistsNamed after the famous Jazz guitar player Django Reinhardt
  4. 4. The frameworkObject-Relational Mapper (ORM)Automatic admin interfaceElegant URL designPowerful templating systemi18n
  5. 5. Big communityDjango has a big community and an extense list of appsSearch for them in http://github.com, http://code.google.comor http://djangopackages.comOther interesting web pages:Django Planet:https://www.planetdjango.orgDjango Community:https://www.djangoproject.com/communityDjango Sites: http://www.djangosites.orgDjango People: http://www.djangopeople.org
  6. 6. Production EnvironmentNginx + Gunicornmod_wsgiFastCGImod_python...
  7. 7. DB BackendOfficially supported:PostreSQLMySQLSQLiteOracle
  8. 8. Using Django
  9. 9. Development EnvironmentDownload it and install Django from http://djangoproject.com/download orBe smart and use Pythons VirtualEnv
  10. 10. VirtualEnvA self-contained virtual environment for Python developmentAdvantages:* Does not touch your Python installation* Keep track of needed modules with a requirements file* Allows to test several package versions
  11. 11. Install VirtualEnv and DjangoInstall VirtualEnv:# apt-get install python-virtualenvCreate a virtual environment:$ virtualenv my_virtual_envUse a virtual environment:$ cd my_virtual_env$ source bin/activateInstall Django inside your virtual environment:$ pip install django
  12. 12. Development
  13. 13. Creating a project$ django-admin.py startproject myprojectmyproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py
  14. 14. Running a project$ ./manage.py runserver... and open in your browser: localhost:8000
  15. 15. DevelopmentDjango projects are composed by appsapps are the projects modules
  16. 16. Creating an applicationInside a project, do:$ python manage.py startapp my_appmy_app/ __init__.py models.py tests.py views.py
  17. 17. Build the DB$ python manage.py syncdb
  18. 18. Project configurationEasy configuration in file settings.py
  19. 19. DevelopmentDjango follows the MTV design patternModel-Template-View
  20. 20. ModelsModels are classes that represent objectsin the databaseAnd youll never have to touch SQL again!
  21. 21. Modelsmodels.py:class Post(models.Model): title = models.CharField(max_length = 500) content = models.TextField() date = models.DateTimeField(auto_now = True) ...
  22. 22. ViewsViews are functions that usually processmodels and render HTMLIts where the magic happens!How to get all posts from the last 5 days and orderthem by descending date?
  23. 23. Viewviews.py:import datetimefrom models import Postdef view_latest_posts(request): # Last 5 days date = datetime.datetime.now() - datetime.timedelta(5) posts = Post.objects.filter(date__gte = date).order_by(-date) return render_to_response(posts/show_posts.html, {posts: posts})
  24. 24. TemplatesThey will help you not repeating yourself!And designers wont have to touch code:
  25. 25. base.html:<html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %}{% endblock %} </body></html>
  26. 26. home.html:{% extends "base.html" %}{% block title %}Homepage{% endblock %}{% block content %} <h3>This will be some main content</h3> {% for post in posts %} <h4>{{ post.title }} on {{ post.date|date:"B d, Y"|upper }}<h4> <p>{{ post.content }}</p> {% endfor %} {% url project.some_app.views.some_view some arguments %}{% endblock %}
  27. 27. URLsIn Django, URLs are part of the design!urls.py use regular expressions to map URLs with views
  28. 28. URLsurls.py:from django.conf.urls import patterns, include, urlurlpatterns = patterns(Project.some_app.views, url(r^$, index), url(r^posts/(?P<r_id>d+)/$, view_latest_posts), url(r^create/$, create), url(r^view/post/(?P<p_id>d+)/$, view, name = view_post),)
  29. 29. Class-based ViewsAllow to structure views and reuse code.They are also faster to use, for common tasks like listingor showing objects:from django.views.generic import DetailView, ListViewurlpatterns = patterns(Project.posts.views, (r^view/(?P<pk>d+)/$, DetailView.as_view(model=Post)), (r^posts/$, ListView.as_view(model=Post)),By default they try to use the templates:post_detail.html and post_list.htmlbut these can be overriden
  30. 30. FormsClasses that represent HTML formsThey allow to easily configure theexpected type of inputs, error messages, labels, etc.
  31. 31. Formsforms.py:class CreatePost(forms.Form): title = forms.CharField(label="Post Title", max_length=500, widget=forms.TextInput(attrs={ class: big_entry })) content = forms.TextField() tags = forms.CharField(required=False)
  32. 32. Formsviews.py:def create_post(request): if request.method == POST: form = CreatePost(request.POST) if form.is_valid(): # Create a new post object with data # from form.cleaned_data return HttpResponseRedirect(/index/) else: form = CreatePost() return render_to_response(create.html, {form: form})
  33. 33. Formscreate_post.html:<form action="/create/" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Create"/></form>
  34. 34. Forms for ModelsForms that are created automatically for modelos, just like:from django.forms import modelsclass PostForm(models.ModelForm): class Meta: model = Post
  35. 35. Automatic AdminTo enable automatic admin, follow the instructionsin your projects URLs (uncomment the admin URLs)and uncomment the admin app in settingsThen, to add a model to the admin, create an admin.pyfile inside an app, for example, for the Post model:from django.contrib import adminfrom models import Postadmin.site.register(Post)
  36. 36. This gives you automatic login...
  37. 37. ... and creation, edition, deletion of objects
  38. 38. Next steps
  39. 39. Django friendly hostsAn extense list can be found at:http://code.djangoproject.com/wiki/DjangoFriendlyWebHostsGoogle AppEngine also makes it easy for Djangoprojects to be deployed:http://appengine.google.com/
  40. 40. HelpDjango Documentation:https://docs.djangoproject.comCheat sheet:http://www.revsys.com/django/cheatsheet/Some books:The Django Book: http://www.djangobook.com/Learning Website Development with Django, PacktPractical Django Projects, ApressPro Django, Apress
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×