Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introduction Django

2,223 views

Published on

Introduction to Django talk given at pyArkansas 2011

Published in: Technology
  • Be the first to comment

Introduction Django

  1. 1. Introduction to Django pyArkansas Wade Austin @k_wade_a
  2. 2. What is Django?“Django is a high-level Python Web framework thatencourages rapid development and clean, pragmaticdesign.” www.djangoproject.com• Created out of the newspaper industry• Help developers build sites fast• Encourage Reuse and Lose Coupling• DRY (don’t repeat yourself)• Minimal Code• Opinionated
  3. 3. Batteries Included django.contrib• Admin Interface for editing data.• Auth module for user accounts• Syndication module for generation of RSS• Static Pages
  4. 4. Active Community• Many Community Contributed Apps• Pinax http://pinaxproject.com/• Django Packages http://djangopackages.com/
  5. 5. Django Projects• A project is your website.• Projects contain the configuration information for your site.• Create a project: django-admin.py startproject [PROJECT_NAME]• Projects contain 3 files: • settings.py - configuration information for your project • urls.py - URL routes defined by your project • manage.py - alias of django-admin.py tuned to your project
  6. 6. Django Applications• Projects are built from Applications• Apps encapsulate some piece of functionality • blog, photo gallery, shopping cart, etc.• Apps can be reused• Apps are Python Packages• manage.py startapp [MY_APP_NAME]
  7. 7. Django Application Components• Models - Your Data• Views - Rules for Accessing Data• Templates - Displays Data• URL Patterns - Maps URLs to Views
  8. 8. Models• Describes the data in your apps• Defined in an app’s models.py file• Map Python Classes to Database Tables• Provides an API for creating, retrieving, changing and deleting data
  9. 9. Blog Data DefinitionCREATE TABLE "blog_category" ( "id" integer NOT NULL PRIMARY KEY, "name" varchar(50) NOT NULL);CREATE TABLE "blog_blogpost" ( "id" integer NOT NULL PRIMARY KEY, "title" varchar(100) NOT NULL, "slug" varchar(50) NOT NULL UNIQUE, "publish_date" datetime NOT NULL, "is_published" bool NOT NULL, "content" text NOT NULL, "category_id" integer NOT NULL REFERENCES "blog_category" ("id"));
  10. 10. Django Hides the SQL• SQL is not consistent across databases• Difficult to store in version control
  11. 11. Model Examplefrom django.db import modelsfrom datetime import datetimeclass Category(models.Model): name = models.CharField(max_length=50)class BlogPost(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) publish_date = models.DateTimeField(default=datetime.now) is_published = models.BooleanField(default=False) content = models.TextField(blank=True) category = models.ForeignKey(Category, related_name=‘posts’)
  12. 12. Creating your database• manage.py syncdb command creates tables from models• Creates all models for any app in your project’s INSTALLED_APPS setting
  13. 13. Querying Modelsposts = BlogPost.objects.all()publshed_posts = BlogPost.objects.filter(is_published=True)news_posts = BlogPost.objects.filter(category__name = News)c = Category( name="News")c.save()
  14. 14. Views• Business Logic• Perform a task and render output (HTML/JSON/XML)• Python function that takes an HttpRequest and returns an HttpResponse• Defined in an app’s views.py file
  15. 15. Hello World Viewfrom django.http import HttpResponsedef hello_world(request): return HttpResponse("Hello World")
  16. 16. Latest Posts Viewfrom django.shortcuts import renderfrom blog.models import BlogPostdef get_latest_posts(request): today = datetime.datetime.now() posts = BlogPost.objects.filter(is_published=True). filter(publish_date__lte=today). order_by(-publish_date) return render( request, blog/latest_posts.html, {posts:posts})
  17. 17. Post Detail Viewfrom django.shortcuts import render, get_object_or_404from blog.models import BlogPostdef blog_post_detail(request, slug): post = get_object_or_404(BlogPost, slug=slug) return render( request, "blog/blogpost_detail.html", {"post":post})
  18. 18. URL Routes• Defines the URLs used in your project• Maps a URL to a View Function• Defined using Regular Expressions• Defined in an app’s urls.py file.
  19. 19. URL Exampleurlpatterns = patterns(, url(r^latest_posts/$, blog.views.get_latest_posts, name=blog_blogpost_latest), url(r^post/(?P<slug>[-w]+)/$, blog.views.blog_post_detail, name=blog_blogpost_detail),)
  20. 20. Templates• Describes the Presentation of your data• Separates Logic from Presentation• Simple Syntax• Designer Friendly• Supports Reuse through inheritance and inclusion• Blocks allow child templates to insert content into parent templates
  21. 21. Template Syntax• Variables: {{variable-name}}• Tags: Perform logic {% include “_form.html” %}• Filters: Operate on data {{post.publish_date|date:"m/d/Y"}}
  22. 22. Template “base.html”<html><head> <title>{% block title %}{% endblock %}My Site</title> <link rel="stylesheet" href="{{STATIC_URL}}css/screen.css" media="screen, projection"/></head><body> <h1>My test site</h1> {% block content %} {% endblock %}</body></html>
  23. 23. Template “latest_posts.html”{% extends "base.html" %}{% block title %}Latest Blog Posts -{% endblock %}{% block content %} <h2>Latest Blog Posts</h1> {% for p in posts %} <h3><a href="{% url blog_blogpost_detail p.slug %}">{{p.title}}</a></h3> <p><strong>Published:</strong> {{p.publish_date|date:"m/d/Y"}} </p> <div class="content"> {{p.content|safe}} </div> {% endfor %}{% endblock %} List of Template Tags and Filters: https://docs.djangoproject.com/en/dev/ref/templates/builtins/
  24. 24. The admin• Not a CMS• Allows site admins to edit content• Auto CRUD views for your models• Easy to customize• Optional. If you don’t like it you can write your own
  25. 25. Admin List
  26. 26. Admin Edit Screen
  27. 27. The admin• add django.contrib.admin to INSTALLED_APPS• Uncomment admin import, discover, and url pattern from PROJECTS urls.py• Create an admin.py file for each app you want to manage
  28. 28. Sample admin.pyfrom django.contrib import adminclass BlogPostAdmin(admin.ModelAdmin): list_display = (title, publish_date, is_published) list_filter = (is_published, publish_date) search_fields = (title, content)admin.site.register(BlogPost, BlogPostAdmin)
  29. 29. Other Stuff• Forms• Caching• Testing
  30. 30. Resources• Official Django Tutorial https://docs.djangoproject.com/en/dev/intro/tutorial01/• Django Documentation https://docs.djangoproject.com/• The Django Book http://www.djangobook.com/• Practical Django Projects https://docs.djangoproject.com/• Pro Django http://prodjango.com/
  31. 31. Thank You Wade Austinhttp://wadeaustin.com @k_wade_a

×