Your SlideShare is downloading. ×
A Basic Django Introduction
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

A Basic Django Introduction


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. Web Development With Django A Basic Introduction Ganga L
  • 2. Python Frameworks  Django  CherryPy  Pylons  Flask  Bottle  Tipfy  Pyramid  Cubic Web  GAE framework
  • 3. Outline What Is Django? Project Structure Data Handling The Admin Interface Django Forms Views Templates
  • 4. What Is Django? High-level framework for rapid web development Complete stack of tools Data modelled with Python classes Production-ready data admin interface, generated dynamically Elegant system for mapping URLs to Python code Generic views’ to handle common requests Clean, powerful template language Components for user authentication, form handling, caching . . .
  • 5. Creating Projects & Apps Creating a project: startproject mysite Creating an app within a project directory: cd mysite ./ startapp poll
  • 6. Project Structure A Python package on your PYTHONPATH Holds project-wide settings in Holds a URL configuration (URLconf) in Contains or references one or more apps
  • 7. App A Python package on your PYTHONPATH (typically created as a subpackage of the project itself) May contain data models in May contain views in May have its own URL configuration in
  • 8. Up & Running Set PYTHONPATH to include parent of your project directory Define new environment variable DJANGO_SETTINGS_MODULE, setting it to project settings (mysite.settings) 3 Try running the development server: / runserver
  • 9. Creating The Database Create database polls in youe database Sync installed apps with database: ./ syncdb
  • 10. Create Project Create Project mysite mysite/ mysite/
  • 11. Create Application python startapp polls polls/
  • 12. Create Models from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField(date published) class Choice(models.Model): poll = models.ForeignKey(Poll) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
  • 13. The Data Model  A description of database layout, as a Python class  Normally represents one database table  Has fields that map onto columns of the table  Many built-in field types  CharField, TextField  IntegerField, FloatField, DecimalField  DateField, DateTimeField, TimeField  EmailField, URLField  ForeignKey . . .
  • 14. Installed App INSTALLED_APPS = ( django.contrib.admin, django.contrib.auth, django.contrib.contenttypes, django.contrib.sessions, django.contrib.messages, django.contrib.staticfiles, polls, ) python syncdb
  • 15. Registering Models in Admin In in the Poll app: from django.contrib import admin from mysite.polls.models import Poll
  • 16. In from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns(, url(r^admin/, include(, )
  • 17. Generic Views Provide ready-made logic for many common tasks:  Issuing a redirect  Displaying a paginated list of objects  Displaying a ‘detail’ page for a single object  Yearly, monthly or daily listing of date-based objects  ‘Latest items’ page for date-based objects  Object creation, updating, deletion (with/without authorisation)
  • 18. Generic Views Example def index(request): return HttpResponse("Hello, world. Youre at the poll index.") from django.conf.urls.defaults import * from polls import views urlpatterns = patterns(, url(r^$, views.index, name=index) ) Main from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns(, url(r^polls/, include(polls.urls)), url(r^admin/, include(, )
  • 19. Creating & Saving Objects  Invoke constructor and call save method:  call create method of Club model manager:poll = Poll(question=what is your DOB? , year=1986) is your DOB? , year=1986)
  • 20. View Function Takes an HTTPRequest object as a parameter Returns an HTTPResponse object to caller Is associated with a particular URL via the URLconf
  • 21. HTTP Responsefrom datetime import datefrom django.http import HttpResponsedef today(request): html = <html><body><h2>%s</h2></body></html> % return HttpResponse(html)from django.shortcuts import render_to_responseFrom mysite.polls.models import Polldef poll_details(request): today = poll_data = Poll.objects.all() return render_to_response(clubs.html, locals(), context_instance = RequestContext(request))
  • 22. Templates  Text files containing  Variables, replaced by values when the template is rendered[  {{ today }}  Filters that modify how values are displayed  {{ today|date:"D d M Y" }}  Tags that control the logic of the rendering process  {% if name == "nick" %}  <p>Hello, Nick!</p>  {% else %}  <p>Who are you?</p>  {% endif %}
  • 23. Template Examplesettings.pyTEMPLATE_DIRS = ( os.path.join(os.path.dirname(__file__), templates), ) templates/club/club_list.html {% extends "base.html" %} {% block title %}Clubs{% endblock %} {% block content %} <h1>Clubs</h1> <ol> {% for club in clubs %} <li>{{ club }}</li> {% endfor %} </ol> {% endblock %}
  • 24. Django Forms A collection of fields that knows how to validate itself and display itself as HTML. Display an HTML form with automatically generated form widgets. Check submitted data against a set of validation rules. Redisplay a form in the case of validation errors. Convert submitted form data to the relevant Python data types.
  • 25. Django Model Forms from django.forms import ModelForm import mysite.polls.models import Poll class PollForm(ModelForm): class Meta: model = Pole
  • 26. A Basic Django Forms
  • 27. Standard
  • 28. Standard
  • 29. Standard
  • 30. Easy
  • 31. Easy
  • 32. Summary We have shown you  The structure of a Django project  How models represent data in Django applications  How data can be stored and queried via model instances  How data can be managed through a dynamic admin interface  How functionality is represent by views, each associated with URLs that match a given pattern  How views render a response using a template
  • 33. Thank You