Introduction to Django


Published on

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

  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Introduction to Django

  1. 1. Introduction to Django Master in Free Software 2012, July 14 2012 Joaquim Rocha <>
  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://djangopackages.comOther interesting web pages:Django Planet:https://www.planetdjango.orgDjango Community: Sites: http://www.djangosites.orgDjango People:
  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 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$ startproject myprojectmyproject/ myproject/
  14. 14. Running a project$ ./ 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 startapp my_appmy_app/
  17. 17. Build the DB$ python syncdb
  18. 18. Project configurationEasy configuration in file
  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. 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. datetimefrom models import Postdef view_latest_posts(request): # Last 5 days date = - 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 {{|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! use regular expressions to map URLs with views
  28. 28. 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. 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. 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
  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: AppEngine also makes it easy for Djangoprojects to be deployed:
  40. 40. HelpDjango Documentation:https://docs.djangoproject.comCheat sheet: books:The Django Book: Website Development with Django, PacktPractical Django Projects, ApressPro Django, Apress