Introduction to Django
Upcoming SlideShare
Loading in...5
×
 

Introduction to Django

on

  • 1,641 views

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

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

Statistics

Views

Total Views
1,641
Slideshare-icon Views on SlideShare
1,641
Embed Views
0

Actions

Likes
3
Downloads
55
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Introduction to Django Introduction to Django Presentation Transcript

    • 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 Djangos official webpage)
    • 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
    • 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.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
    • 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 VirtualEnv
    • 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
    • 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
    • Development
    • Creating a project$ django-admin.py startproject myprojectmyproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py
    • 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.py
    • 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() date = models.DateTimeField(auto_now = True) ...
    • 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?
    • 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})
    • 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 content %}{% endblock %} </body></html>
    • 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 %}
    • 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^$, 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),)
    • 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
    • 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, widget=forms.TextInput(attrs={ class: big_entry })) content = forms.TextField() tags = forms.CharField(required=False)
    • 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})
    • Formscreate_post.html:<form action="/create/" method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Create"/></form>
    • Forms for ModelsForms that are created automatically for modelos, just like:from django.forms import modelsclass PostForm(models.ModelForm): class Meta: model = Post
    • 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)
    • 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 AppEngine also makes it easy for Djangoprojects to be deployed:http://appengine.google.com/
    • 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