This document provides an introduction to web development with the Django framework. It outlines Django's project structure, how it handles data with models, and its built-in admin interface. It also covers views, templates, forms, and generic views. Django allows defining models as Python classes to represent the database structure. It provides a production-ready admin interface to manage data. URLs are mapped to views, which can render templates to generate responses. Forms validate and display data. Generic views handle common tasks like displaying object lists.
In this document
Powered by AI
Introduction to web development using Django, outlining the purpose and presenter.
List of various Python frameworks including Django, CherryPy, Flask, and others.
Overview of topics to be discussed, including Django definition, project structure, data handling, admin interface, forms, views, and templates.
Django is a high-level framework for rapid web development featuring dynamic admin interfaces, URL mapping, generic views, and user authentication.
Instructions for creating a project and app within Django using command line tools.
Description of Django project structure including PYTHONPATH, settings.py, and URL configuration.
Definition of an app in Django, outlining its structure and components such as models and views.
Steps to set environment variables and run the development server for Django applications.
Steps to create a database and synchronize it with Django apps using manage.py.
Details of creating a Django project structure showing files like manage.py and urls.py.
Instructions for creating an application within a Django project and its basic file structure.
Example of Django data models defining fields and data relationships using Python.
Overview of how database layouts are modeled as Python classes with various field types.
Configuration for installed apps in Django, including enabling the polls app.
Instructions on how to register models to appear in the Django admin interface.
Setting up URL patterns for the Django admin interface and app routing.
Explanation of generic views for common tasks such as redirects and object listings.
Example implementation of Django generic views and URL routing.
How to create and save objects in Django models using constructor and manager methods.
Definition and role of view functions, describing HTTPRequest and HTTPResponse.
Example of generating an HTML response using Django and accessing model data.
Description of Django templates, variables, filters, and control logic.
Example template structure including extending base templates and dynamic content.
Overview of Django forms for validating user input and displaying HTML forms.
Using ModelForm to create forms based on Django models.
Basic structure and functionality of Django forms.
Code examples for standard views in Django applications.
Code examples for simplified views in Django applications.
Summary of key concepts covered in the presentation regarding Django project structure, models, views, and templates.
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:
django-admin.py startproject mysite
Creating an app within a project directory:
cd mysite
./manage.py startapp poll
6.
Project Structure
A Python package on your PYTHONPATH
Holds project-wide settings in settings.py
Holds a URL configuration (URLconf) in urls.py
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 models.py
May contain views in views.py
May have its own URL configuration in urls.py
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:
/manage.py runserver
9.
Creating The Database
Create database polls in youe database
Sync installed apps with database:
./manage.py syncdb
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 . . .
Registering Models inAdmin
In admin.py in the Poll app:
from django.contrib import admin
from mysite.polls.models import Poll
admin.site.register(Poll)
16.
In urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
)
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
views.py
def index(request):
return HttpResponse("Hello, world. You're at the poll index.")
Url.py
from django.conf.urls.defaults import *
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index')
)
Main URL.py
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(admin.site.urls)),
)
19.
Creating & SavingObjects
Invoke constructor and call save method:
call create method of Club model manager:
poll = Poll(question='what is your DOB? ', year='1986)
poll.save()
Poll.objects.create(question='what 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 Response
from datetimeimport date
from django.http import HttpResponse
def today(request):
html = '<html><body><h2>%s</h2></body></html>' % date.today()
return HttpResponse(html)
from django.shortcuts import render_to_response
From mysite.polls.models import Poll
def poll_details(request):
today = date.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 Example
settings.py
TEMPLATE_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
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