SlideShare a Scribd company logo
1 of 49
Building a Dynamic
Website Using Django
        Nathan Eror
       Hush Labs, LLC




                        © 2007 Hush Labs, LLC
                                           1
Who am I?




            © 2007 Hush Labs, LLC
                               2
Let’s Build
Something!
              © 2007 Hush Labs, LLC
                                 3
Time to Get Started

1. Download and Install Python & Django
2. Install sqlite if you don’t have it yet
3. Crank up your editor and get ready to code




                                                © 2007 Hush Labs, LLC
                                                                   4
> django-admin.py startproject barcamplive
> cd barcamplive
> ./manage.py startapp liveblog
> mkdir -p templates public/uploads




                                             © 2007 Hush Labs, LLC
                                                                5
File: settings.py


DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'barcamplive.db'
import os.path, sys
PROJECT_ROOT = os.path.abspath(os.path.dirname(sys.argv[0])))
MEDIA_ROOT = quot;%s/publicquot; % PROJECT_ROOT
MEDIA_URL = 'http://localhost:8000/public'
ADMIN_MEDIA_PREFIX = '/admin/public/'
ROOT_URLCONF = 'urls'
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'liveblog'
)
TEMPLATE_DIRS = (
  quot;%s/templatesquot; % PROJECT_ROOT,
)



                                                                © 2007 Hush Labs, LLC
                                                                                   6
Start With the
 Data Model

                 © 2007 Hush Labs, LLC
                                    7
File: liveblog/.py

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime

class Post(models.Model):
  title = models.CharField(blank=False, null=False, maxlength=2048)
  author = models.ForeignKey(User, related_name='posts')
  created = models.DateTimeField(u'Date Created', blank=False, null=False,
                                 default=datetime.now)
  slug = models.SlugField(prepopulate_from=(quot;titlequot;,))

  def __str__(self):
    return self.title

class PostItem(models.Model):
  post = models.ForeignKey(Post, related_name='items')
  created = models.DateTimeField(u'Date Created', blank=False,
                                 default=datetime.now)
  image = models.ImageField(upload_to=quot;uploadsquot;, blank=True)
  content = models.TextField(blank=True)

  def __str__(self):
    return quot;Post Item for '%s' created at %squot; % 
           (self.post.title, self.created.strftime('%I:%M %p %Z'))

                                                                     © 2007 Hush Labs, LLC
                                                                                        8
postgresql mysql sqlite
                        oracle mssql
>>> u = User.objects.get(username='admin')


       Django Models (ORM)
>>> p = Post(title='Django is fun!',slug='django-is-fun',author=u)
>>> p.save()
>>> i = PostItem(content='Woo Hoo!')
>>> p.items.add(i)
>>> Post.objects.all()
[<Post: Django is fun!>]
>>> p2 = Post.objects.get(slug='django-is-fun')
>>> p2.items.all()
[<PostItem: Post Item for 'Django is fun!' created at 03:27 PM >]
>>> p2.delete()
>>> Post.objects.count()
0L
>>> PostItem.objects.count()
0L
                                                             © 2007 Hush Labs, LLC
                                                                                9
> ./manage.py syncdb
> ./manage.py runserver




                          © 2007 Hush Labs, LLC
                                            10
The Django
Admin Site

             © 2007 Hush Labs, LLC
                               11
© 2007 Hush Labs, LLC
                  12
Django URLs

              © 2007 Hush Labs, LLC
                                13
File: urls.py


from django.conf.urls.defaults import *
from django.conf import settings

urlpatterns = patterns('',
  # Example:
  # (r'^barcamplive/', include('barcamplive.foo.urls')),

    # Uncomment this for admin:
    (r'^admin/', include('django.contrib.admin.urls')),
)




                                                           © 2007 Hush Labs, LLC
                                                                             14
© 2007 Hush Labs, LLC
                  15
File: settings.py


DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'barcamplive.db'
import os.path, sys
PROJECT_ROOT = os.path.abspath(os.path.dirname(sys.argv[0])))
MEDIA_ROOT = quot;%s/publicquot; % PROJECT_ROOT
ROOT_URLCONF = 'urls'
MEDIA_URL = 'http://localhost:8000/public'
ADMIN_MEDIA_PREFIX = '/admin/public/'
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.admin',
    'liveblog'
)
TEMPLATE_DIRS = (
  quot;%s/templatesquot; % PROJECT_ROOT,
)



                                                                © 2007 Hush Labs, LLC
                                                                                  16
© 2007 Hush Labs, LLC
                  17
© 2007 Hush Labs, LLC
                  18
File: liveblog/models.py

class Post(models.Model):
  title = models.CharField(blank=False, null=False, maxlength=2048)
  author = models.ForeignKey(User, related_name='posts')
  created = models.DateTimeField(u'Date Created', blank=False, null=False,
                                 default=datetime.now)
  slug = models.SlugField(prepopulate_from=(quot;titlequot;,))

  class Admin:
    list_display = ('title', 'author', 'created')
    list_filter = ('created', 'author')
    search_fields = ('title',)
    date_hierarchy = 'created'




                                                                   © 2007 Hush Labs, LLC
                                                                                     19
File: liveblog/models.py

class PostItem(models.Model):
  post = models.ForeignKey(Post, related_name='items')
  created = models.DateTimeField(u'Date Created', blank=False,
                                 default=datetime.now)
  image = models.ImageField(upload_to=quot;uploadsquot;, blank=True)
  content = models.TextField(blank=True)

  class Admin:
    list_display = ('post', 'created')
    list_filter = ('created', 'post')
    search_fields = ('content',)
    date_hierarchy = 'created'




                                                                 © 2007 Hush Labs, LLC
                                                                                   20
File: liveblog/models.py

class PostItem(models.Model):
  post = models.ForeignKey(Post, related_name='items',
                           edit_inline=models.TABULAR, num_in_admin=1)
  created = models.DateTimeField(u'Date Created', blank=False,
                                 default=datetime.now)
  image = models.ImageField(upload_to=quot;uploadsquot;, blank=True, core=True)
  content = models.TextField(blank=True, core=True)




                                                                   © 2007 Hush Labs, LLC
                                                                                     21
What About Our
   Visitors?




                 © 2007 Hush Labs, LLC
                                   22
File: templates/base.html

<?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?>
<!DOCTYPE html PUBLIC quot;-//W3C//DTD XHTML 1.1//ENquot;
     quot;http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtdquot;>
<html xmlns=quot;http://www.w3.org/1999/xhtmlquot; xml:lang=quot;enquot;>
<head>
     <title>BarCamp Houston Live!</title>
     <link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;/public/css/reset-fonts-grids.cssquot;>
     <link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;/public/css/base-min.cssquot;>
  <link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;/public/css/live.cssquot;>
</head>
<body>
  <div id=quot;docquot; class=quot;yui-t4quot;>
    <div id=quot;hdquot;><h1><a href=quot;/quot;>The BarCamp Liveblog</a></h1></div>
    <div id=quot;bdquot;>
       <div id=quot;yui-mainquot;>
          <div class=quot;yui-bquot;>
            <!-- The main content goes here -->
          </div>
       </div>
       <div id=quot;sidebarquot; class=quot;yui-bquot;>
         <!-- The sidebar goes here -->
       </div>
    </div>
    <div id=quot;ftquot;><div id=quot;copyrightquot;>&copy;2007 <a href=quot;http://www.hushlabs.comquot;>Hush Labs, LLC</
a><br/>Header image adapted from flickr user <a href=quot;http://www.flickr.com/photos/eschipul/
254400673/quot;>eschipul's</a>.</div></div>
  </div>
</body>
</html>




                                                                                            © 2007 Hush Labs, LLC
                                                                                                              23
File: urls.py


urlpatterns = patterns('',
  url(r'^$', direct_to_template, {'template': 'base.html'},
      name='index'),

    (r'^admin/', include('django.contrib.admin.urls')),
    (r'^public/(?P<path>.*)$', 'django.views.static.serve',
     {'document_root':settings.MEDIA_ROOT}),
)




                                                              © 2007 Hush Labs, LLC
                                                                                24
archive_week               archive_day

  redirect_to            object_list

 direct_to_template   object_detail


      Generic Views
      create_object   archive_month

   delete_object        archive_index

 update_object            archive_year

                                  © 2007 Hush Labs, LLC
                                                    25
File: urls.py


from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
  url(r'^$', direct_to_template, {'template': 'base.html'},
      name='index'),

    (r'^admin/', include('django.contrib.admin.urls')),
    (r'^public/(?P<path>.*)$', 'django.views.static.serve',
     {'document_root':settings.MEDIA_ROOT}),
)




                                                              © 2007 Hush Labs, LLC
                                                                                26
© 2007 Hush Labs, LLC
                  27
{{ Variables|Filters}}      {% Tags %}


           Templates
              Inheritance
                                   © 2007 Hush Labs, LLC
                                                     28
File: templates/base.html

<div id=quot;yui-mainquot;>
   <div class=quot;yui-bquot;>
      {% block content %}{% endblock %}
   </div>
</div>




File: templates/liveblog/post_list.html

{% extends quot;base.htmlquot; %}
{% block content %}
<div id=quot;post_listquot;>
<h1>Current Liveblogs</h1>
{% if object_list %}
<ul>
  {% for post in object_list %}
     <li><a href=quot;{% url post-detail post.slug %}quot;>{{post.title}}</a></li>
  {% endfor %}
</ul>
{% else %}
<h3>There are no blogs yet!</h3>
{% endif %}
</div>
{% endblock %}




                                                                             © 2007 Hush Labs, LLC
                                                                                               29
File: urls.py


from django.views.generic.list_detail import object_list

urlpatterns = patterns('',
  url(r'^$', object_list,
      {'queryset':Post.objects.all(),'allow_empty':True},
      name='index')
)




                                                            © 2007 Hush Labs, LLC
                                                                              30
<a href=quot;{% url post-detail post.slug %}quot;>{{post.title}}</a>

  File: urls.py


  from django.views.generic.list_detail import object_detail
                    <a href=quot;quot;>Django is fun!</a>
  urlpatterns = patterns('',
    url(r'^$', direct_to_template, {'template': 'base.html'},
        name='index'),
    url(r'^post/(?P<slug>.*)/$', object_detail,
        {'queryset':Post.objects}, name='post-detail'),
  )
File: templates/liveblog/post_detail.html

{% extends quot;base.htmlquot; %}
{% block content %}
<div class=quot;postquot;>
  <div class=quot;titlequot;>{{object.title}}</div>
  <div class=quot;taglinequot;>Started at {{object.created}}</div>
  <div class=quot;contentquot;>
    {% for item in object.items %}
    <div class=quot;post_itemquot;>
       <div class=quot;item_taglinequot;>Added on {{item.created}}</div>
       {% if item.image %}<div class=quot;item_imagequot;><img src=quot;/public/{{item.image}}quot;></div>{% endif %}
       <div class=quot;item_contentquot;>{{item.content|linebreaks}}</div>
       <br style=quot;clear:both;quot;/>
    </div>
    {% endfor %}
  </div>
</div>
{% endblock %}

                                                                                             © 2007 Hush Labs, LLC
                                                                                                               31
© 2007 Hush Labs, LLC
                  32
Views
django.http.HttpRequest




  View Function


django.http.HttpResponse




                           © 2007 Hush Labs, LLC
                                             33
File: urls.py


from liveblog import views

urlpatterns = patterns('',
  url(r'^$', direct_to_template, {'template': 'base.html'},
      name='index'),
  url(r'^post/(?P<slug>.*)/$', views.post_detail,
      name='post-detail'),
)


File: liveblog/views.py


from models import Post
from django.shortcuts import get_object_or_404, render_to_response

def post_detail(request, slug):
  post = get_object_or_404(Post, slug=slug)
  items = post.items.all()
  return render_to_response('liveblog/post_detail.html',
                            {'post':post, 'items':items})


                                                              © 2007 Hush Labs, LLC
                                                                                34
File: templates/liveblog/post_detail.html

{% extends quot;base.htmlquot; %}
{% block content %}
<div class=quot;postquot;>
  <div class=quot;titlequot;>{{post.title}}</div>
  <div class=quot;taglinequot;>Started at {{post.created}}</div>
  <div class=quot;contentquot;>
    {% for item in items %}
    <div class=quot;post_itemquot;>
       <div class=quot;item_taglinequot;>Added on {{item.created}}</div>
       {% if item.image %}<div class=quot;item_imagequot;><img src=quot;/public/{{item.image}}quot;></div>{% endif %}
       <div class=quot;item_contentquot;>{{item.content|linebreaks}}</div>
       <br style=quot;clear:both;quot;/>
    </div>
    {% endfor %}
  </div>
</div>
{% endblock %}




                                                                                             © 2007 Hush Labs, LLC
                                                                                                               35
© 2007 Hush Labs, LLC
                  36
“I want the admin to
 look like the rest of
       the site.”

                     © 2007 Hush Labs, LLC
                                       37
File: urls.py


from django.contrib.auth.views import login, logout

urlpatterns = patterns('',
  url(r'^accounts/login/$', login, name='login'),
  url(r'^accounts/logout/$', logout, name='logout'),
)



File: templates/registration/login.html

{% extends quot;base.htmlquot; %}
{% block content %}
  <form action=quot;quot; method=quot;postquot; accept-charset=quot;utf-8quot;>
    {% if form.username.errors %}{{ form.username.html_error_list }}{% endif %}
    <p><label for=quot;id_usernamequot;>Username:</label> {{form.username}}</p>
    {% if form.password.errors %}{{ form.password.html_error_list }}{% endif %}
    <p><label for=quot;id_passwordquot;>Password:</label> {{form.password}}</p>
    <p><input type=quot;submitquot; value=quot;Loginquot;></p>
  </form>
{% endblock %}




File: templates/registration/logged_out.html

{% extends quot;base.htmlquot; %}
{% block content %}
  <h1>You are now logged out</h1>
{% endblock %}



                                                                                  © 2007 Hush Labs, LLC
                                                                                                    38
© 2007 Hush Labs, LLC
                  39
© 2007 Hush Labs, LLC
                  40
File: templates/base.html

<body>
  <div id=quot;docquot; class=quot;yui-t4quot;>
    <div id=quot;hdquot;><h1><a href=quot;/quot;>The BarCamp Liveblog</a></h1></div>
    <div id=quot;bdquot;>
       <div id=quot;yui-mainquot;>
          <div class=quot;yui-bquot;>
          {% block content %}{% endblock %}
          </div>
       </div>
       <div id=quot;sidebarquot; class=quot;yui-bquot;>
         <ul>
           <li><a href=quot;{% url add-post %}quot;>Add a Blog Post</a></li>
           {% block extralinks %}{% endblock %}
           {% if user.is_authenticated %}
           <li><a href=quot;{% url logout %}quot;>Logout</a></li>
           {% else %}
           <li><a href=quot;{% url login %}quot;>Login</a></li>
           {% endif %}
         </ul>
       </div>
    </div>
    <div id=quot;ftquot;><div id=quot;copyrightquot;>&copy;2007 <a href=quot;http://www.hushlabs.comquot;>Hush Labs, LLC</
a><br/>Header image adapted from flickr user <a href=quot;http://www.flickr.com/photos/eschipul/
254400673/quot;>eschipul's</a>.</div></div>
  </div>
</body>




                                                                                            © 2007 Hush Labs, LLC
                                                                                                              41
Forms

        © 2007 Hush Labs, LLC
                          42
File: urls.py


urlpatterns = patterns('',
  url(r'^add_post/$', views.add_post, name='add-post'),
)

File: templates/post_form.html

{% extends quot;base.htmlquot; %}
{% block content %}
<form action=quot;quot; method=quot;postquot; accept-charset=quot;utf-8quot;>
  {{form.title.errors}}
  <p>{{form.title.label_tag}}: {{form.title}}</p>
  {{form.slug.errors}}
  <p>{{form.slug.label_tag}}: {{form.slug}}</p>
  {{form.author.as_hidden}}
  <p><input type=quot;submitquot; value=quot;Addquot;></p>
</form>
{% endblock %}




                                                          © 2007 Hush Labs, LLC
                                                                            43
File: liveblog/views.py

from   django import newforms as forms
from   django.contrib.auth.decorators import login_required
from   django.http import HttpResponseRedirect
from   django.core.urlresolvers import reverse

@login_required
def add_post(request):
  PostForm = forms.form_for_model(Post, fields=('title', 'slug', 'author'))
  if request.method == 'POST':
    form = PostForm(request.POST)
    if form.is_valid():
      new_post = form.save()
      return HttpResponseRedirect(reverse('post-detail', args=[new_post.slug]))
  else:
    form = PostForm(initial={'author':request.user.id})
  return render_to_response('liveblog/post_form.html', {'form':form})




                                                                                  © 2007 Hush Labs, LLC
                                                                                                    44
File: urls.py


urlpatterns = patterns('',
  url(r'^post/(?P<slug>.+)/add_item/', views.add_item, name='add-post-item'),
)


File: templates/liveblog/post_item_form.html

{% extends quot;liveblog/post_detail.htmlquot; %}
{% block newitemform %}
<form enctype=quot;multipart/form-dataquot; action=quot;quot; method=quot;postquot; accept-charset=quot;utf-8quot;>
  {{form.content.errors}}
  <p>{{form.content.label_tag}}: {{form.content}}</p>
  {{form.image.errors}}
  <p>{{form.image.label_tag}}: {{form.image}}</p>
  <p><input type=quot;submitquot; value=quot;Addquot;></p>
</form>
{% endblock %}


File: templates/liveblog/post_detail.html

{% for item in items %}
<div class=quot;post_itemquot;>
  <div class=quot;item_taglinequot;>Added on {{item.created}}</div>
  {% if item.image %}
    <div class=quot;item_imagequot;><img src=quot;/public/{{item.image}}quot;></div>
  {% endif %}
  <div class=quot;item_contentquot;>{{item.content|linebreaks}}</div>
  <br style=quot;clear:both;quot;/>
</div>
{% endfor %}
{% block newitemform %}{% endblock %}
{% block extralinks %}
<li><a href=quot;{% url add-post-item post.slug %}quot;>Add an item</a></li>
{% endblock %}
                                                                                      © 2007 Hush Labs, LLC
                                                                                                        45
File: liveblog/views.py

class PostItemForm(forms.Form):
  image = forms.ImageField(required=False)
  content = forms.CharField(widget=forms.Textarea(), required=True)

  def save(self, post):
    uploaded_file = self.cleaned_data['image']
    new_item = PostItem(post=post, content=self.cleaned_data['content'])
    new_item.save_image_file(uploaded_file.filename, uploaded_file.content)
    new_item.save()
    return new_item


@login_required
def add_item(request, slug):
  post = Post.objects.get(slug=slug)
  items = post.items.all()
  if request.method == quot;POSTquot;:
    form = PostItemForm(request.POST, request.FILES)
    if form.is_valid():
      new_item = form.save(post)
      return HttpResponseRedirect(reverse('post-detail', args=[new_item.post.slug]))
  else:
    form = PostItemForm()
  return render_to_response('liveblog/post_item_form.html', locals())




                                                                                  © 2007 Hush Labs, LLC
                                                                                                    46
© 2007 Hush Labs, LLC
                  47
That’s It!

             48
Nathan Eror
 neror@hushlabs.com
http://natuba.com/neror


                          49

More Related Content

What's hot

Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To DjangoJay Graves
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask PresentationParag Mujumdar
 
What is Django | Django Tutorial for Beginners | Python Django Training | Edu...
What is Django | Django Tutorial for Beginners | Python Django Training | Edu...What is Django | Django Tutorial for Beginners | Python Django Training | Edu...
What is Django | Django Tutorial for Beginners | Python Django Training | Edu...Edureka!
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoIlian Iliev
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOdoo
 
Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh AgarwalDjango app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh Agarwalratneshsinghparihar
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django frameworkKnoldus Inc.
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
기본적인 테스트에 대한 pytest 자동화 접근
기본적인 테스트에 대한 pytest 자동화 접근기본적인 테스트에 대한 pytest 자동화 접근
기본적인 테스트에 대한 pytest 자동화 접근SangIn Choung
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django frameworkflapiello
 

What's hot (20)

Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Python/Flask Presentation
Python/Flask PresentationPython/Flask Presentation
Python/Flask Presentation
 
Arquitetura Node com NestJS
Arquitetura Node com NestJSArquitetura Node com NestJS
Arquitetura Node com NestJS
 
What is Django | Django Tutorial for Beginners | Python Django Training | Edu...
What is Django | Django Tutorial for Beginners | Python Django Training | Edu...What is Django | Django Tutorial for Beginners | Python Django Training | Edu...
What is Django | Django Tutorial for Beginners | Python Django Training | Edu...
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Svelte
SvelteSvelte
Svelte
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
 
Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh AgarwalDjango app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh Agarwal
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
Svelte JS introduction
Svelte JS introductionSvelte JS introduction
Svelte JS introduction
 
Net core
Net coreNet core
Net core
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
 
Basic Python Django
Basic Python DjangoBasic Python Django
Basic Python Django
 
기본적인 테스트에 대한 pytest 자동화 접근
기본적인 테스트에 대한 pytest 자동화 접근기본적인 테스트에 대한 pytest 자동화 접근
기본적인 테스트에 대한 pytest 자동화 접근
 
Les collections en Java
Les collections en JavaLes collections en Java
Les collections en Java
 
Web application development with Django framework
Web application development with Django frameworkWeb application development with Django framework
Web application development with Django framework
 
Java 17
Java 17Java 17
Java 17
 

Viewers also liked

Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and DjangoMichael Pirnat
 
Building a custom cms with django
Building a custom cms with djangoBuilding a custom cms with django
Building a custom cms with djangoYann Malet
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC FrameworkBala Kumar
 
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Innovecs
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django ArchitectureRami Sayar
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
Introducción a la teoría general de sistemas oscar johansen b.
Introducción a la teoría general de sistemas   oscar johansen b.Introducción a la teoría general de sistemas   oscar johansen b.
Introducción a la teoría general de sistemas oscar johansen b.marisol2829
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Scott Wlaschin
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSHannes Hapke
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application FrameworkSimon Willison
 
Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with PythonLarry Cai
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 

Viewers also liked (16)

Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Building a custom cms with django
Building a custom cms with djangoBuilding a custom cms with django
Building a custom cms with django
 
Django introduction
Django introductionDjango introduction
Django introduction
 
Django in the Real World
Django in the Real WorldDjango in the Real World
Django in the Real World
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
 
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
Reliable Python REST API (by Volodymyr Hotsyk) - Web Back-End Tech Hangout - ...
 
Rest api with Python
Rest api with PythonRest api with Python
Rest api with Python
 
Scalable Django Architecture
Scalable Django ArchitectureScalable Django Architecture
Scalable Django Architecture
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
Introducción a la teoría general de sistemas oscar johansen b.
Introducción a la teoría general de sistemas   oscar johansen b.Introducción a la teoría general de sistemas   oscar johansen b.
Introducción a la teoría general de sistemas oscar johansen b.
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
 
Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)Functional Programming Patterns (NDC London 2014)
Functional Programming Patterns (NDC London 2014)
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJS
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
 
Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with Python
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Similar to Building a Dynamic Website Using Django

Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4DEVCON
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Paul Bearne
 
Pyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web appsPyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web appsDylan Jay
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsAlessandro Molina
 
Google App Engine with Gaelyk
Google App Engine with GaelykGoogle App Engine with Gaelyk
Google App Engine with GaelykChoong Ping Teo
 
Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexyananelson
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosIgor Sobreira
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVCAlive Kuo
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Kris Wallsmith
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gearsdion
 
PyCon APAC - Django Test Driven Development
PyCon APAC - Django Test Driven DevelopmentPyCon APAC - Django Test Driven Development
PyCon APAC - Django Test Driven DevelopmentTudor Munteanu
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocratJonathan Linowes
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal coreMarcin Wosinek
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It TodayDoris Chen
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentationipolevoy
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQueryBastian Feder
 

Similar to Building a Dynamic Website Using Django (20)

Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919
 
Pyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web appsPyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web apps
 
TurboGears2 Pluggable Applications
TurboGears2 Pluggable ApplicationsTurboGears2 Pluggable Applications
TurboGears2 Pluggable Applications
 
Google App Engine with Gaelyk
Google App Engine with GaelykGoogle App Engine with Gaelyk
Google App Engine with Gaelyk
 
Refresh Austin - Intro to Dexy
Refresh Austin - Intro to DexyRefresh Austin - Intro to Dexy
Refresh Austin - Intro to Dexy
 
Django
DjangoDjango
Django
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3
 
Future of Web Apps: Google Gears
Future of Web Apps: Google GearsFuture of Web Apps: Google Gears
Future of Web Apps: Google Gears
 
PyCon APAC - Django Test Driven Development
PyCon APAC - Django Test Driven DevelopmentPyCon APAC - Django Test Driven Development
PyCon APAC - Django Test Driven Development
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat12 core technologies you should learn, love, and hate to be a 'real' technocrat
12 core technologies you should learn, love, and hate to be a 'real' technocrat
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
 

Recently uploaded

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Recently uploaded (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Building a Dynamic Website Using Django

  • 1. Building a Dynamic Website Using Django Nathan Eror Hush Labs, LLC © 2007 Hush Labs, LLC 1
  • 2. Who am I? © 2007 Hush Labs, LLC 2
  • 3. Let’s Build Something! © 2007 Hush Labs, LLC 3
  • 4. Time to Get Started 1. Download and Install Python & Django 2. Install sqlite if you don’t have it yet 3. Crank up your editor and get ready to code © 2007 Hush Labs, LLC 4
  • 5. > django-admin.py startproject barcamplive > cd barcamplive > ./manage.py startapp liveblog > mkdir -p templates public/uploads © 2007 Hush Labs, LLC 5
  • 6. File: settings.py DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = 'barcamplive.db' import os.path, sys PROJECT_ROOT = os.path.abspath(os.path.dirname(sys.argv[0]))) MEDIA_ROOT = quot;%s/publicquot; % PROJECT_ROOT MEDIA_URL = 'http://localhost:8000/public' ADMIN_MEDIA_PREFIX = '/admin/public/' ROOT_URLCONF = 'urls' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'liveblog' ) TEMPLATE_DIRS = ( quot;%s/templatesquot; % PROJECT_ROOT, ) © 2007 Hush Labs, LLC 6
  • 7. Start With the Data Model © 2007 Hush Labs, LLC 7
  • 8. File: liveblog/.py from django.db import models from django.contrib.auth.models import User from datetime import datetime class Post(models.Model): title = models.CharField(blank=False, null=False, maxlength=2048) author = models.ForeignKey(User, related_name='posts') created = models.DateTimeField(u'Date Created', blank=False, null=False, default=datetime.now) slug = models.SlugField(prepopulate_from=(quot;titlequot;,)) def __str__(self): return self.title class PostItem(models.Model): post = models.ForeignKey(Post, related_name='items') created = models.DateTimeField(u'Date Created', blank=False, default=datetime.now) image = models.ImageField(upload_to=quot;uploadsquot;, blank=True) content = models.TextField(blank=True) def __str__(self): return quot;Post Item for '%s' created at %squot; % (self.post.title, self.created.strftime('%I:%M %p %Z')) © 2007 Hush Labs, LLC 8
  • 9. postgresql mysql sqlite oracle mssql >>> u = User.objects.get(username='admin') Django Models (ORM) >>> p = Post(title='Django is fun!',slug='django-is-fun',author=u) >>> p.save() >>> i = PostItem(content='Woo Hoo!') >>> p.items.add(i) >>> Post.objects.all() [<Post: Django is fun!>] >>> p2 = Post.objects.get(slug='django-is-fun') >>> p2.items.all() [<PostItem: Post Item for 'Django is fun!' created at 03:27 PM >] >>> p2.delete() >>> Post.objects.count() 0L >>> PostItem.objects.count() 0L © 2007 Hush Labs, LLC 9
  • 10. > ./manage.py syncdb > ./manage.py runserver © 2007 Hush Labs, LLC 10
  • 11. The Django Admin Site © 2007 Hush Labs, LLC 11
  • 12. © 2007 Hush Labs, LLC 12
  • 13. Django URLs © 2007 Hush Labs, LLC 13
  • 14. File: urls.py from django.conf.urls.defaults import * from django.conf import settings urlpatterns = patterns('', # Example: # (r'^barcamplive/', include('barcamplive.foo.urls')), # Uncomment this for admin: (r'^admin/', include('django.contrib.admin.urls')), ) © 2007 Hush Labs, LLC 14
  • 15. © 2007 Hush Labs, LLC 15
  • 16. File: settings.py DATABASE_ENGINE = 'sqlite3' DATABASE_NAME = 'barcamplive.db' import os.path, sys PROJECT_ROOT = os.path.abspath(os.path.dirname(sys.argv[0]))) MEDIA_ROOT = quot;%s/publicquot; % PROJECT_ROOT ROOT_URLCONF = 'urls' MEDIA_URL = 'http://localhost:8000/public' ADMIN_MEDIA_PREFIX = '/admin/public/' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'liveblog' ) TEMPLATE_DIRS = ( quot;%s/templatesquot; % PROJECT_ROOT, ) © 2007 Hush Labs, LLC 16
  • 17. © 2007 Hush Labs, LLC 17
  • 18. © 2007 Hush Labs, LLC 18
  • 19. File: liveblog/models.py class Post(models.Model): title = models.CharField(blank=False, null=False, maxlength=2048) author = models.ForeignKey(User, related_name='posts') created = models.DateTimeField(u'Date Created', blank=False, null=False, default=datetime.now) slug = models.SlugField(prepopulate_from=(quot;titlequot;,)) class Admin: list_display = ('title', 'author', 'created') list_filter = ('created', 'author') search_fields = ('title',) date_hierarchy = 'created' © 2007 Hush Labs, LLC 19
  • 20. File: liveblog/models.py class PostItem(models.Model): post = models.ForeignKey(Post, related_name='items') created = models.DateTimeField(u'Date Created', blank=False, default=datetime.now) image = models.ImageField(upload_to=quot;uploadsquot;, blank=True) content = models.TextField(blank=True) class Admin: list_display = ('post', 'created') list_filter = ('created', 'post') search_fields = ('content',) date_hierarchy = 'created' © 2007 Hush Labs, LLC 20
  • 21. File: liveblog/models.py class PostItem(models.Model): post = models.ForeignKey(Post, related_name='items', edit_inline=models.TABULAR, num_in_admin=1) created = models.DateTimeField(u'Date Created', blank=False, default=datetime.now) image = models.ImageField(upload_to=quot;uploadsquot;, blank=True, core=True) content = models.TextField(blank=True, core=True) © 2007 Hush Labs, LLC 21
  • 22. What About Our Visitors? © 2007 Hush Labs, LLC 22
  • 23. File: templates/base.html <?xml version=quot;1.0quot; encoding=quot;UTF-8quot;?> <!DOCTYPE html PUBLIC quot;-//W3C//DTD XHTML 1.1//ENquot; quot;http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtdquot;> <html xmlns=quot;http://www.w3.org/1999/xhtmlquot; xml:lang=quot;enquot;> <head> <title>BarCamp Houston Live!</title> <link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;/public/css/reset-fonts-grids.cssquot;> <link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;/public/css/base-min.cssquot;> <link rel=quot;stylesheetquot; type=quot;text/cssquot; href=quot;/public/css/live.cssquot;> </head> <body> <div id=quot;docquot; class=quot;yui-t4quot;> <div id=quot;hdquot;><h1><a href=quot;/quot;>The BarCamp Liveblog</a></h1></div> <div id=quot;bdquot;> <div id=quot;yui-mainquot;> <div class=quot;yui-bquot;> <!-- The main content goes here --> </div> </div> <div id=quot;sidebarquot; class=quot;yui-bquot;> <!-- The sidebar goes here --> </div> </div> <div id=quot;ftquot;><div id=quot;copyrightquot;>&copy;2007 <a href=quot;http://www.hushlabs.comquot;>Hush Labs, LLC</ a><br/>Header image adapted from flickr user <a href=quot;http://www.flickr.com/photos/eschipul/ 254400673/quot;>eschipul's</a>.</div></div> </div> </body> </html> © 2007 Hush Labs, LLC 23
  • 24. File: urls.py urlpatterns = patterns('', url(r'^$', direct_to_template, {'template': 'base.html'}, name='index'), (r'^admin/', include('django.contrib.admin.urls')), (r'^public/(?P<path>.*)$', 'django.views.static.serve', {'document_root':settings.MEDIA_ROOT}), ) © 2007 Hush Labs, LLC 24
  • 25. archive_week archive_day redirect_to object_list direct_to_template object_detail Generic Views create_object archive_month delete_object archive_index update_object archive_year © 2007 Hush Labs, LLC 25
  • 26. File: urls.py from django.views.generic.simple import direct_to_template urlpatterns = patterns('', url(r'^$', direct_to_template, {'template': 'base.html'}, name='index'), (r'^admin/', include('django.contrib.admin.urls')), (r'^public/(?P<path>.*)$', 'django.views.static.serve', {'document_root':settings.MEDIA_ROOT}), ) © 2007 Hush Labs, LLC 26
  • 27. © 2007 Hush Labs, LLC 27
  • 28. {{ Variables|Filters}} {% Tags %} Templates Inheritance © 2007 Hush Labs, LLC 28
  • 29. File: templates/base.html <div id=quot;yui-mainquot;> <div class=quot;yui-bquot;> {% block content %}{% endblock %} </div> </div> File: templates/liveblog/post_list.html {% extends quot;base.htmlquot; %} {% block content %} <div id=quot;post_listquot;> <h1>Current Liveblogs</h1> {% if object_list %} <ul> {% for post in object_list %} <li><a href=quot;{% url post-detail post.slug %}quot;>{{post.title}}</a></li> {% endfor %} </ul> {% else %} <h3>There are no blogs yet!</h3> {% endif %} </div> {% endblock %} © 2007 Hush Labs, LLC 29
  • 30. File: urls.py from django.views.generic.list_detail import object_list urlpatterns = patterns('', url(r'^$', object_list, {'queryset':Post.objects.all(),'allow_empty':True}, name='index') ) © 2007 Hush Labs, LLC 30
  • 31. <a href=quot;{% url post-detail post.slug %}quot;>{{post.title}}</a> File: urls.py from django.views.generic.list_detail import object_detail <a href=quot;quot;>Django is fun!</a> urlpatterns = patterns('', url(r'^$', direct_to_template, {'template': 'base.html'}, name='index'), url(r'^post/(?P<slug>.*)/$', object_detail, {'queryset':Post.objects}, name='post-detail'), ) File: templates/liveblog/post_detail.html {% extends quot;base.htmlquot; %} {% block content %} <div class=quot;postquot;> <div class=quot;titlequot;>{{object.title}}</div> <div class=quot;taglinequot;>Started at {{object.created}}</div> <div class=quot;contentquot;> {% for item in object.items %} <div class=quot;post_itemquot;> <div class=quot;item_taglinequot;>Added on {{item.created}}</div> {% if item.image %}<div class=quot;item_imagequot;><img src=quot;/public/{{item.image}}quot;></div>{% endif %} <div class=quot;item_contentquot;>{{item.content|linebreaks}}</div> <br style=quot;clear:both;quot;/> </div> {% endfor %} </div> </div> {% endblock %} © 2007 Hush Labs, LLC 31
  • 32. © 2007 Hush Labs, LLC 32
  • 33. Views django.http.HttpRequest View Function django.http.HttpResponse © 2007 Hush Labs, LLC 33
  • 34. File: urls.py from liveblog import views urlpatterns = patterns('', url(r'^$', direct_to_template, {'template': 'base.html'}, name='index'), url(r'^post/(?P<slug>.*)/$', views.post_detail, name='post-detail'), ) File: liveblog/views.py from models import Post from django.shortcuts import get_object_or_404, render_to_response def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) items = post.items.all() return render_to_response('liveblog/post_detail.html', {'post':post, 'items':items}) © 2007 Hush Labs, LLC 34
  • 35. File: templates/liveblog/post_detail.html {% extends quot;base.htmlquot; %} {% block content %} <div class=quot;postquot;> <div class=quot;titlequot;>{{post.title}}</div> <div class=quot;taglinequot;>Started at {{post.created}}</div> <div class=quot;contentquot;> {% for item in items %} <div class=quot;post_itemquot;> <div class=quot;item_taglinequot;>Added on {{item.created}}</div> {% if item.image %}<div class=quot;item_imagequot;><img src=quot;/public/{{item.image}}quot;></div>{% endif %} <div class=quot;item_contentquot;>{{item.content|linebreaks}}</div> <br style=quot;clear:both;quot;/> </div> {% endfor %} </div> </div> {% endblock %} © 2007 Hush Labs, LLC 35
  • 36. © 2007 Hush Labs, LLC 36
  • 37. “I want the admin to look like the rest of the site.” © 2007 Hush Labs, LLC 37
  • 38. File: urls.py from django.contrib.auth.views import login, logout urlpatterns = patterns('', url(r'^accounts/login/$', login, name='login'), url(r'^accounts/logout/$', logout, name='logout'), ) File: templates/registration/login.html {% extends quot;base.htmlquot; %} {% block content %} <form action=quot;quot; method=quot;postquot; accept-charset=quot;utf-8quot;> {% if form.username.errors %}{{ form.username.html_error_list }}{% endif %} <p><label for=quot;id_usernamequot;>Username:</label> {{form.username}}</p> {% if form.password.errors %}{{ form.password.html_error_list }}{% endif %} <p><label for=quot;id_passwordquot;>Password:</label> {{form.password}}</p> <p><input type=quot;submitquot; value=quot;Loginquot;></p> </form> {% endblock %} File: templates/registration/logged_out.html {% extends quot;base.htmlquot; %} {% block content %} <h1>You are now logged out</h1> {% endblock %} © 2007 Hush Labs, LLC 38
  • 39. © 2007 Hush Labs, LLC 39
  • 40. © 2007 Hush Labs, LLC 40
  • 41. File: templates/base.html <body> <div id=quot;docquot; class=quot;yui-t4quot;> <div id=quot;hdquot;><h1><a href=quot;/quot;>The BarCamp Liveblog</a></h1></div> <div id=quot;bdquot;> <div id=quot;yui-mainquot;> <div class=quot;yui-bquot;> {% block content %}{% endblock %} </div> </div> <div id=quot;sidebarquot; class=quot;yui-bquot;> <ul> <li><a href=quot;{% url add-post %}quot;>Add a Blog Post</a></li> {% block extralinks %}{% endblock %} {% if user.is_authenticated %} <li><a href=quot;{% url logout %}quot;>Logout</a></li> {% else %} <li><a href=quot;{% url login %}quot;>Login</a></li> {% endif %} </ul> </div> </div> <div id=quot;ftquot;><div id=quot;copyrightquot;>&copy;2007 <a href=quot;http://www.hushlabs.comquot;>Hush Labs, LLC</ a><br/>Header image adapted from flickr user <a href=quot;http://www.flickr.com/photos/eschipul/ 254400673/quot;>eschipul's</a>.</div></div> </div> </body> © 2007 Hush Labs, LLC 41
  • 42. Forms © 2007 Hush Labs, LLC 42
  • 43. File: urls.py urlpatterns = patterns('', url(r'^add_post/$', views.add_post, name='add-post'), ) File: templates/post_form.html {% extends quot;base.htmlquot; %} {% block content %} <form action=quot;quot; method=quot;postquot; accept-charset=quot;utf-8quot;> {{form.title.errors}} <p>{{form.title.label_tag}}: {{form.title}}</p> {{form.slug.errors}} <p>{{form.slug.label_tag}}: {{form.slug}}</p> {{form.author.as_hidden}} <p><input type=quot;submitquot; value=quot;Addquot;></p> </form> {% endblock %} © 2007 Hush Labs, LLC 43
  • 44. File: liveblog/views.py from django import newforms as forms from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse @login_required def add_post(request): PostForm = forms.form_for_model(Post, fields=('title', 'slug', 'author')) if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): new_post = form.save() return HttpResponseRedirect(reverse('post-detail', args=[new_post.slug])) else: form = PostForm(initial={'author':request.user.id}) return render_to_response('liveblog/post_form.html', {'form':form}) © 2007 Hush Labs, LLC 44
  • 45. File: urls.py urlpatterns = patterns('', url(r'^post/(?P<slug>.+)/add_item/', views.add_item, name='add-post-item'), ) File: templates/liveblog/post_item_form.html {% extends quot;liveblog/post_detail.htmlquot; %} {% block newitemform %} <form enctype=quot;multipart/form-dataquot; action=quot;quot; method=quot;postquot; accept-charset=quot;utf-8quot;> {{form.content.errors}} <p>{{form.content.label_tag}}: {{form.content}}</p> {{form.image.errors}} <p>{{form.image.label_tag}}: {{form.image}}</p> <p><input type=quot;submitquot; value=quot;Addquot;></p> </form> {% endblock %} File: templates/liveblog/post_detail.html {% for item in items %} <div class=quot;post_itemquot;> <div class=quot;item_taglinequot;>Added on {{item.created}}</div> {% if item.image %} <div class=quot;item_imagequot;><img src=quot;/public/{{item.image}}quot;></div> {% endif %} <div class=quot;item_contentquot;>{{item.content|linebreaks}}</div> <br style=quot;clear:both;quot;/> </div> {% endfor %} {% block newitemform %}{% endblock %} {% block extralinks %} <li><a href=quot;{% url add-post-item post.slug %}quot;>Add an item</a></li> {% endblock %} © 2007 Hush Labs, LLC 45
  • 46. File: liveblog/views.py class PostItemForm(forms.Form): image = forms.ImageField(required=False) content = forms.CharField(widget=forms.Textarea(), required=True) def save(self, post): uploaded_file = self.cleaned_data['image'] new_item = PostItem(post=post, content=self.cleaned_data['content']) new_item.save_image_file(uploaded_file.filename, uploaded_file.content) new_item.save() return new_item @login_required def add_item(request, slug): post = Post.objects.get(slug=slug) items = post.items.all() if request.method == quot;POSTquot;: form = PostItemForm(request.POST, request.FILES) if form.is_valid(): new_item = form.save(post) return HttpResponseRedirect(reverse('post-detail', args=[new_item.post.slug])) else: form = PostItemForm() return render_to_response('liveblog/post_item_form.html', locals()) © 2007 Hush Labs, LLC 46
  • 47. © 2007 Hush Labs, LLC 47