web development with django - basics presentation

27
Web development with Django © Shrinath Shenoy

Upload: shrinath-shenoy

Post on 26-Jun-2015

703 views

Category:

Software


1 download

DESCRIPTION

Basic getting started introductory slides on Django.

TRANSCRIPT

Page 1: Web development with django - Basics Presentation

Web development with Django

© Shrinath Shenoy

Page 2: Web development with django - Basics Presentation

What is Django

Django can be used with databases like Postgresql, MySQL, sqlite, MongoDB, Oracle etc..

Django is a MVC like framework ( Django community call it as MTV - Model, View, Template ) written in pure python

Page 3: Web development with django - Basics Presentation

Who are using Django

Mozilla ( support.mozilla.com, addons.mozilla.org )Google ( developers.google.com, app engine cloud sql )DisqusPinterestInstagrambitbucketnewyorktimes.com (represent)washingtonpost.comguardian.co.ukdeveloper.vodafone.comnationalgeographic.com

Page 4: Web development with django - Basics Presentation

Creating a django project

Start a new project fromdjango-admin.py startproject projectname

It will create project folders in the following structure

projectname/ manage.py projectname/ __init__.py settings.py urls.py wsgi.py

Page 5: Web development with django - Basics Presentation

Django Project Structure

python manage.py startapp appname

projectname/ manage.py appname/ __init__.py models.py tests.py views.py projectname/ __init__.py settings.py urls.py wsgi.py

Page 6: Web development with django - Basics Presentation

settings.py

This contains all the settings related to the project. Like DB username-password-connection-port, middlewares, logs, dev settings, media path etc.

The settings.py file is used as default configuration file while running the server. If you have some other settings file then you can tell the server to use that by setting the environment vairable DJANGO_SETTINGS_MODULE

Page 7: Web development with django - Basics Presentation

urls.py

• URL patterns are definied in this file.• URL patterns will be made up of regular expressions of the url patterns. • The function/view that needs to be called are mapped here.• Best Practice : Maintain a urls.py inside each app to avoid the global urls.py mess

Page 8: Web development with django - Basics Presentation

A typical urls mapping looks like this

from django.conf.urls import patterns, url

urlpatterns += patterns('', urlpatterns = ( url(r'^$', views.index, name='index'), )

Page 9: Web development with django - Basics Presentation

views.py

The request lands here after the url requested is mapped to a view through middlewares.

There are two types of view. That a user can opt for depending on the requirement.1. Function Based View2. Classbased view

Function based views are normal python functions that take request and curresponding custom parameter if any.Class Based views are the special views that is required to be inheriting the django's predefined view/any other class that satisfy the condition to map the url to a class based view ( Better to inherit the view class given by django :) )

Page 10: Web development with django - Basics Presentation

• There are lot of built in views that can be used accordingly. ( e.g. listview - if you want just to list the objects of a model that satisfy a queryset )

• url definition will take function based view ( FBV ) as second argument. This will make the view function gets called for that url. Where as Class based view's as_view() function should be feed to url definition. The reason is given below.

• Class Based Views ( CBV ) has the intelligence to find the method used in request ( get, post or any other ) and dispatche the data come along with the request to curresonding method.

Page 11: Web development with django - Basics Presentation

• Each view must return a response or raise the relevant exeption if any.

• response can contain the django template, file, JSON objects or even just HTTP Status codes.

Page 12: Web development with django - Basics Presentation

A typical Django FBV would look like this

from django.http import HttpResponseimport datetime

def current_datetime(request): now = datetime.datetime.now() html = "<html><body>Its now

%s</body></html>" % now return HttpResponse(html)

Page 13: Web development with django - Basics Presentation

A typical Django CBV would look like this

import datetimefrom django.http import HttpResponsefrom django.views.generic import View

class ShowDateView(View): def get(request): now = datetime.datetime.now() html = "<html><body>Its now

%s</body></html>" % now return HttpResponse(html)

Page 14: Web development with django - Basics Presentation

models.py

Models.py file is the place to put the details about the DB tables that we need in our app.

Models can be imagined as DB Table - definition written in python :)

Models are the normal python classes that inherit from the Django "Model" class found in django.db.models module.

The class attributes/member-variables defines the columns and data type of their curresponding db tables.

Page 15: Web development with django - Basics Presentation

• models will have thier own "manager" objects that will be used to query the table.

• Django ORM provides the "query functions" in each models through thier "manager" objects.

• Each model object will have their save() method to save the model "instance" into database.

• models have built in validators which will validate the model object values against their datatype and constraints.

Page 16: Web development with django - Basics Presentation

A typical django model would look like

from django.db import models

class UserProfile(models.Model): first_name = models.CharField(max_lenght=10) last_name = models.CharField(max_lenght=10) phone_number = models.IntegerField(null=True)

Page 17: Web development with django - Basics Presentation

Availble Built in Fields in Django models

AutoFieldBigIntegerFieldBooleanFieldCharFieldCommaSeparatedIntegerFieldDateFieldDateTimeFieldDecimalFieldEmailFieldFileField

Page 18: Web development with django - Basics Presentation

forms.py

Django forms which is used to process web form data are similar to django model classes. But django froms deal with the incoming data from client rather than database.Similar to Django models django forms are python classes inheriting from Django's django.form module

Page 19: Web development with django - Basics Presentation

A django form declaration would look like

from django import forms

class LoginForm(forms.Form): username = forms.CharField(max_length=12) password = forms.CharField(max_lenght=12, att)

Page 20: Web development with django - Basics Presentation

Django Forms built in Fields

BooleanFieldCharField ChoiceFieldDateField DateTimeFieldEmailField FileFieldFloatField ImageFieldIPAddressField GenericIPAddressFieldTypedMultipleChoiceField NullBooleanFieldSlugField TimeFieldTypedChoiceField DecimalFieldFilePathField IntegerFieldMultipleChoiceField RegexFieldURLField

Page 21: Web development with django - Basics Presentation

templates

Django templates are the files (Usually HTML ) which allow us to insert the django variables inside them and write very minimalistic processing like iterating over a loop, trimming the string, adding integers inside them etc.Django templates are designed to make it reusable. Like a class, you can inherite a template and override the portions of it.

Django template engine comes with built in tags and filters which can be used to process the data before rendering. Even django allows you to create your own custom tags and filters. So that you can define your custom behaviors in the template.

Page 22: Web development with django - Basics Presentation

Django templates should be written in such a way that only rendering process will be held in that. No complex logical algorithm shoul be handled inside the templates.Django template are designed such that it uses the less of programming language, and more of the designing part so that any web designer knowing only creating HTML/CSS/Javascript can develop it without having the exposure to the python.

Page 23: Web development with django - Basics Presentation

Django Principles

DRY ( Don't Repeat Yourself )

Loose Coupling

Less Code

Explicit is better than implicit

Infinite flexibility in url

Separate logic from presentation

Be decoupled from HTML

Page 24: Web development with django - Basics Presentation

Benifits/Pros of using Django

Easy to understand and easily maintainable code

Write less do more with python-django combination.

Lot of opensource plugins available that can be used along with django. You just need to import and use it in your code.

Page 25: Web development with django - Basics Presentation

Django has lot of built-ins which are more commonly needed functionalities in a web app along with additional goodies.• User authentication and password management• Pagination• Form-Model validation• Caching• Admin Panel• Session management• Protection via clickjacking and cross site

Page 26: Web development with django - Basics Presentation

• Localization• Email Integration• RSS Feeds Integration• Sitemap Integration• CSV/PDF save/export integration• Geographical Query Support

Page 27: Web development with django - Basics Presentation

Thank You..!!

: )