SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
Django 1.2.3 on python 2.7 and mysql
Making Simple Blog
By ivan sugiarto
ivan@wirekom.co.id
Setting up Django
 Go to directory on where your project will be created
 Write command (on shell or command prompt) django-
admin.py startproject testsite, this will create
folder containing the project and files that are needed to make
project and don’t forget to make admin account
 Issue command python manage.py runserver on
testsite folder to test the Django installation
 Set up your database in settings.py located in
testsite folder
 Issue python manage.py syncdb to test your
configuration
Creating An Application/Module
 We will create blog module
 Go to testsite directory and type command python manage.py startapp blog
 Go to blog folder and open model.py
 Write from django.db import models and from
django.contrib.auth.models import User on top
 Write
class Post(models.Model):
author = models.ForeignKey(User)
date = models.DateTimeField()
title = models.CharField(max_length=100)
post = models.TextField()
#making the list title so python not displaying raw data
def __str__(self):
return self.title
 Edit settings.py and add test testsite.blog in the INSTALLED_APPS section
 Run command python manage.py syncdb to update database
Make Admin Page
 Open settings.py and add django.contrib.admin
 type the command python manage.py syncdb
 Edit urls.py to enable admin, add
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
)
 Issue the command python manage.py runserver and check
http://127.0.0.1:8000/admin to ensure your admin is working, if
you are asked for login then you are on the right path
Make admin page for blog
 Create admin.py on blog directory and write
from django.contrib import admin
from testsite.blog.models import Post
class PostAdmin(admin.ModelAdmin):
#makin order by
date_hierarchy = 'date‘
#making list display field
list_display = ('author', 'date', 'title')
#making search on the top corner
search_fields = ('title', 'post')
#making filter on the right corner
list_filter = ('author', 'date')
#register on the admin page
admin.site.register(Post, PostAdmin)
 Run server (python manage.py runserver) and go to
http://127.0.0.1:8000/admin/blog/post/
Admin preview
Urls.py
 Settings on root urls.py (my best practice though :D)
(r'^blog/', include('testsite.blog.urls')),
 Blog is the root, and it will include urls.py in the blog folder
 Urls.py in blog folder will contain this for example
#(http://127.0.0.1:8000/blog/detail/post_id(integer)/whatever',
(function name in view.py)), will be coded as follows
(r'^detail/(?P<post_id>d+)/$', detail),
Templating
 Create directory on test site called template and edit
settings.py
 Add this following
TEMPLATE_DIRS = (
‘path_to_your_development_folder/testsite/templates’,
)
 On blog/views.py add this following
from django.template.loader import get_template
from django.template import Context, loader
from django.shortcuts import render_to_response, get_object_or_404
def detail(request, post_id):
p = get_object_or_404(Post, pk=post_id)
return render_to_response('blog/detail.html', {'post': p},
context_instance=RequestContext(request))
 Create detail.html in template/blog/ (continued)
Create detail.html
 Type this
<h2>{{ post }}</h2>
<p>{{ post.post }}</p>
<b>{{ post.author }}</b> wrote {{ post.post|wordcount
}} words on {{ post.date|date }} at {{ post.date|time
}}
<ul>
<li><a href='/blog/update/{{ post.id }}'>
edit</a></li>
<li><a href='/blog/delete/{{ post.id }}'>
delete</a></li>
</ul>
 Cek link
http://127.0.0.1:8000/blog/detail/<your_post_id>
Pagination (1)
 Use admin interface to make posts
 Create template in template/blog/list.html
 Add url pattern in blog/url.py so it became like this
from django.conf.urls.defaults import *
from testsite.blog.models import Post
from testsite.blog.views import *
urlpatterns = patterns('django.views.generic.date_based',
(r'^add', add_blog
),
(r'^list/(?P<page>d+)/$', list),
(r'^detail/(?P<post_id>d+)/$', detail),
)
Pagination(2)
 To add pagination, edit blog/views.py, first add the following lines
from django.core.paginator import Paginator
 Next make the list function like this
def list(request, page = 1):
page = int(page)
post_list = Paginator(Post.objects.all(), 5, allow_empty_first_page=True)
post_page = post_list.page(page)
num = post_page.start_index()
count = post_page.end_index()
has_previous = post_page.has_previous()
has_next = post_page.has_next()
return render_to_response(
'blog/list.html',
{
'post_list': post_page.object_list,
'has_previous': has_previous,
'previous_page': page - 1,
'has_next': has_next,
'next_page': page + 1,
'page' : page,
'num' : num,
'count' : count
}
)
Pagination (3) create the template
 Create In template/blog/list.html, and write the following
{% if post_list %}
{{ page }}
{{ num }}
{{ count }}
<a href='/blog/add/'> add </a>
<ul>
{% for post in post_list %}
<li><a href='/blog/detail/{{ post.id }}'>
{{post.title}}</a></li>
{% endfor %}
</ul>
{% if has_previous %}
<a href='/blog/list/{{ previous_page }}'>Previous</a>
{% if has_next %} | {% endif %}
{% endif %}
{% if has_next %}
<a href='/blog/list/{{ next_page }}'>Next</a>
{% endif %}
{% else %}
<p>No links found.</p>
{% endif %}
Check blog/urls.py
 Before continuing, please make sure that the urls.py looks like this
from django.conf.urls.defaults import *
from testsite.blog.models import Post
from testsite.blog.views import *
urlpatterns = patterns('',
(r'^add', add_blog
),
(r'^list/(?P<page>d+)/$', list),
(r'^detail/(?P<post_id>d+)/$', detail),
(r'^update/(?P<post_id>d+)/$', update),
(r'^delete/(?P<post_id>d+)/$', delete)
)
Creating Form Create (1) The Model
 In blog/model.py add this
#top
from django.forms import ModelForm
#under class post
class PostForm(ModelForm):
class Meta:
model = Post
#the fields on the form, you can add fields, but must
corespond with field in Post
fields = ('title', 'post')
Creating Form Create (2) The View Top
 Add this lines
#top
from django.http import HttpResponse,
HttpResponseRedirect
from django.shortcuts import render_to_response,
get_object_or_404
from django.template.loader import get_template
from django.template import Context, loader,
RequestContext
from testsite.blog.models import *
from django.contrib.auth.models import User
from datetime import datetime
from django.views.decorators.csrf import
csrf_protect
from django.core.paginator import Paginator
Creating Form Create (2) The View Bottom
#bottom
def add_blog(request):
form = PostForm()
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
form = PostForm(request.POST)
blog = form.save(commit=False)
blog.author = User.objects.get(id = request.user.id)
blog.date = datetime.now()
blog.save()
return HttpResponseRedirect("/blog/list/1")
else:
return render_to_response('blog/add_blog.html', {'error': True,
'form': form})
else:
return render_to_response('blog/add_blog.html', {'error': True,
'form': form})
Creating Form Create (3) The Template
<html>
<head>
<title>blog</title>
</head>
<body>
{% if error %}
<p style="color: red;">Please submit a blog.</p>
{% endif %}
{% csrf_token %}
<form action="" method="post">
<table>
{{ form.as_table }}
</table>
<input type="submit" value ="submit">
</form>
</body>
</html>
Creating Form Update (1) The View
 Add this code
def update(request, post_id):
post = Post.objects.get(pk=post_id)
if request.method == 'POST':
form = PostForm(request.POST, instance=post)
if form.is_valid():
form.save()
return HttpResponseRedirect("/blog/list/1")
else:
return render_to_response('blog/add_blog.html',
{'error': True, 'form': form})
else:
form = PostForm(instance=post)
return render_to_response('blog/add_blog.html',
{'error': True, 'form': form})
Creating Form Update (2) The Template
<html>
<head>
<title>blog</title>
</head>
<body>
{% if error %}
<p style="color: red;">Please submit a blog.</p>
{% endif %}
{% csrf_token %}
<form action="" method="post">
<table>
{{ form.as_table }}
</table>
<input type="submit" value ="submit">
</form>
</body>
</html>
Creating Form Delete (1) The View
def delete(request, post_id):
p = Post.objects.get(pk=post_id)
p.delete()
return HttpResponseRedirect("/blog/list/1")
Misc
 You can grab the files in
http://wirekom.co.id/uploads/testsite.zip

Weitere ähnliche Inhalte

Was ist angesagt?

A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your AppLuca Mearelli
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slidesMasterCode.vn
 
Flask patterns
Flask patternsFlask patterns
Flask patternsit-people
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful CodeGreggPollack
 
WordPress plugin #2
WordPress plugin #2WordPress plugin #2
WordPress plugin #2giwoolee
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Jacob Kaplan-Moss
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the WildDavid Glick
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolGordon Forsythe
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
Plug in development
Plug in developmentPlug in development
Plug in developmentLucky Ali
 
3 introduction-php-mvc-cakephp-m3-getting-started-slides
3 introduction-php-mvc-cakephp-m3-getting-started-slides3 introduction-php-mvc-cakephp-m3-getting-started-slides
3 introduction-php-mvc-cakephp-m3-getting-started-slidesMasterCode.vn
 
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindiaComplaints
 
Cakephp's Cache
Cakephp's CacheCakephp's Cache
Cakephp's Cachevl
 
浜松Rails3道場 其の参 Controller編
浜松Rails3道場 其の参 Controller編浜松Rails3道場 其の参 Controller編
浜松Rails3道場 其の参 Controller編Masakuni Kato
 

Was ist angesagt? (20)

A Little Backbone For Your App
A Little Backbone For Your AppA Little Backbone For Your App
A Little Backbone For Your App
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides4 introduction-php-mvc-cakephp-m4-controllers-slides
4 introduction-php-mvc-cakephp-m4-controllers-slides
 
Flask patterns
Flask patternsFlask patterns
Flask patterns
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talkKyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful Code
 
WordPress plugin #2
WordPress plugin #2WordPress plugin #2
WordPress plugin #2
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 
Dexterity in the Wild
Dexterity in the WildDexterity in the Wild
Dexterity in the Wild
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
Plug in development
Plug in developmentPlug in development
Plug in development
 
3 introduction-php-mvc-cakephp-m3-getting-started-slides
3 introduction-php-mvc-cakephp-m3-getting-started-slides3 introduction-php-mvc-cakephp-m3-getting-started-slides
3 introduction-php-mvc-cakephp-m3-getting-started-slides
 
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephp
 
Cakephp's Cache
Cakephp's CacheCakephp's Cache
Cakephp's Cache
 
浜松Rails3道場 其の参 Controller編
浜松Rails3道場 其の参 Controller編浜松Rails3道場 其の参 Controller編
浜松Rails3道場 其の参 Controller編
 
Django
DjangoDjango
Django
 
CakePHP
CakePHPCakePHP
CakePHP
 
CodeIgniter 3.0
CodeIgniter 3.0CodeIgniter 3.0
CodeIgniter 3.0
 

Ähnlich wie Django

Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Djangofool2nd
 
Django tech-talk
Django tech-talkDjango tech-talk
Django tech-talkdtdannen
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction DjangoWade Austin
 
WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practicesmarkparolisi
 
Intro to Pylons / Pyramid
Intro to Pylons / PyramidIntro to Pylons / Pyramid
Intro to Pylons / PyramidEric Paxton
 
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheetLam Hoang
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django IntroductionGanga Ram
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesLeonardo Fernandes
 
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimDjango Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimMir Nazim
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django projectXiaoqi Zhao
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009Ferenc Szalai
 

Ähnlich wie Django (20)

Django crush course
Django crush course Django crush course
Django crush course
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Django Vs Rails
Django Vs RailsDjango Vs Rails
Django Vs Rails
 
Django
DjangoDjango
Django
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
Django tech-talk
Django tech-talkDjango tech-talk
Django tech-talk
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
WordPress Structure and Best Practices
WordPress Structure and Best PracticesWordPress Structure and Best Practices
WordPress Structure and Best Practices
 
Django
DjangoDjango
Django
 
Intro to Pylons / Pyramid
Intro to Pylons / PyramidIntro to Pylons / Pyramid
Intro to Pylons / Pyramid
 
Django quickstart
Django quickstartDjango quickstart
Django quickstart
 
Django cheat sheet
Django cheat sheetDjango cheat sheet
Django cheat sheet
 
A Basic Django Introduction
A Basic Django IntroductionA Basic Django Introduction
A Basic Django Introduction
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico Ces
 
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir NazimDjango Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
Django Introduction Osscamp Delhi September 08 09 2007 Mir Nazim
 
Build and deploy Python Django project
Build and deploy Python Django projectBuild and deploy Python Django project
Build and deploy Python Django project
 
Django
DjangoDjango
Django
 
Django web framework
Django web frameworkDjango web framework
Django web framework
 
Django tutorial 2009
Django tutorial 2009Django tutorial 2009
Django tutorial 2009
 

Kürzlich hochgeladen

integrity in personal relationship (1).pdf
integrity in personal relationship (1).pdfintegrity in personal relationship (1).pdf
integrity in personal relationship (1).pdfAmitRout25
 
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?Mikko Kangassalo
 
English basic for beginners Future tenses .pdf
English basic for beginners Future tenses .pdfEnglish basic for beginners Future tenses .pdf
English basic for beginners Future tenses .pdfbromerom1
 
Call Girls Dubai O525547819 Favor Dubai Call Girls Agency
Call Girls Dubai O525547819 Favor Dubai Call Girls AgencyCall Girls Dubai O525547819 Favor Dubai Call Girls Agency
Call Girls Dubai O525547819 Favor Dubai Call Girls Agencykojalkojal131
 
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...JeylaisaManabat1
 
ingrediendts needed in preparing dessert and sweet sauces
ingrediendts needed in preparing dessert and sweet saucesingrediendts needed in preparing dessert and sweet sauces
ingrediendts needed in preparing dessert and sweet saucesJessicaEscao
 
The 5 sec rule - Mel Robins (Hindi Summary)
The 5 sec rule - Mel Robins (Hindi Summary)The 5 sec rule - Mel Robins (Hindi Summary)
The 5 sec rule - Mel Robins (Hindi Summary)Shakti Savarn
 
Spiritual Life Quote from Shiva Negi
Spiritual Life Quote from Shiva Negi Spiritual Life Quote from Shiva Negi
Spiritual Life Quote from Shiva Negi OneDay18
 
Benefits of Co working & Shared office space in India
Benefits of Co working & Shared office space in IndiaBenefits of Co working & Shared office space in India
Benefits of Co working & Shared office space in IndiaBrantfordIndia
 

Kürzlich hochgeladen (9)

integrity in personal relationship (1).pdf
integrity in personal relationship (1).pdfintegrity in personal relationship (1).pdf
integrity in personal relationship (1).pdf
 
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
Virtue ethics & Effective Altruism: What can EA learn from virtue ethics?
 
English basic for beginners Future tenses .pdf
English basic for beginners Future tenses .pdfEnglish basic for beginners Future tenses .pdf
English basic for beginners Future tenses .pdf
 
Call Girls Dubai O525547819 Favor Dubai Call Girls Agency
Call Girls Dubai O525547819 Favor Dubai Call Girls AgencyCall Girls Dubai O525547819 Favor Dubai Call Girls Agency
Call Girls Dubai O525547819 Favor Dubai Call Girls Agency
 
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
Module-2-Lesson-2-COMMUNICATION-AIDS-AND-STRATEGIES-USING-TOOLS-OF-TECHNOLOGY...
 
ingrediendts needed in preparing dessert and sweet sauces
ingrediendts needed in preparing dessert and sweet saucesingrediendts needed in preparing dessert and sweet sauces
ingrediendts needed in preparing dessert and sweet sauces
 
The 5 sec rule - Mel Robins (Hindi Summary)
The 5 sec rule - Mel Robins (Hindi Summary)The 5 sec rule - Mel Robins (Hindi Summary)
The 5 sec rule - Mel Robins (Hindi Summary)
 
Spiritual Life Quote from Shiva Negi
Spiritual Life Quote from Shiva Negi Spiritual Life Quote from Shiva Negi
Spiritual Life Quote from Shiva Negi
 
Benefits of Co working & Shared office space in India
Benefits of Co working & Shared office space in IndiaBenefits of Co working & Shared office space in India
Benefits of Co working & Shared office space in India
 

Django

  • 1. Django 1.2.3 on python 2.7 and mysql Making Simple Blog By ivan sugiarto ivan@wirekom.co.id
  • 2. Setting up Django  Go to directory on where your project will be created  Write command (on shell or command prompt) django- admin.py startproject testsite, this will create folder containing the project and files that are needed to make project and don’t forget to make admin account  Issue command python manage.py runserver on testsite folder to test the Django installation  Set up your database in settings.py located in testsite folder  Issue python manage.py syncdb to test your configuration
  • 3. Creating An Application/Module  We will create blog module  Go to testsite directory and type command python manage.py startapp blog  Go to blog folder and open model.py  Write from django.db import models and from django.contrib.auth.models import User on top  Write class Post(models.Model): author = models.ForeignKey(User) date = models.DateTimeField() title = models.CharField(max_length=100) post = models.TextField() #making the list title so python not displaying raw data def __str__(self): return self.title  Edit settings.py and add test testsite.blog in the INSTALLED_APPS section  Run command python manage.py syncdb to update database
  • 4. Make Admin Page  Open settings.py and add django.contrib.admin  type the command python manage.py syncdb  Edit urls.py to enable admin, add from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), )  Issue the command python manage.py runserver and check http://127.0.0.1:8000/admin to ensure your admin is working, if you are asked for login then you are on the right path
  • 5. Make admin page for blog  Create admin.py on blog directory and write from django.contrib import admin from testsite.blog.models import Post class PostAdmin(admin.ModelAdmin): #makin order by date_hierarchy = 'date‘ #making list display field list_display = ('author', 'date', 'title') #making search on the top corner search_fields = ('title', 'post') #making filter on the right corner list_filter = ('author', 'date') #register on the admin page admin.site.register(Post, PostAdmin)  Run server (python manage.py runserver) and go to http://127.0.0.1:8000/admin/blog/post/
  • 7. Urls.py  Settings on root urls.py (my best practice though :D) (r'^blog/', include('testsite.blog.urls')),  Blog is the root, and it will include urls.py in the blog folder  Urls.py in blog folder will contain this for example #(http://127.0.0.1:8000/blog/detail/post_id(integer)/whatever', (function name in view.py)), will be coded as follows (r'^detail/(?P<post_id>d+)/$', detail),
  • 8. Templating  Create directory on test site called template and edit settings.py  Add this following TEMPLATE_DIRS = ( ‘path_to_your_development_folder/testsite/templates’, )  On blog/views.py add this following from django.template.loader import get_template from django.template import Context, loader from django.shortcuts import render_to_response, get_object_or_404 def detail(request, post_id): p = get_object_or_404(Post, pk=post_id) return render_to_response('blog/detail.html', {'post': p}, context_instance=RequestContext(request))  Create detail.html in template/blog/ (continued)
  • 9. Create detail.html  Type this <h2>{{ post }}</h2> <p>{{ post.post }}</p> <b>{{ post.author }}</b> wrote {{ post.post|wordcount }} words on {{ post.date|date }} at {{ post.date|time }} <ul> <li><a href='/blog/update/{{ post.id }}'> edit</a></li> <li><a href='/blog/delete/{{ post.id }}'> delete</a></li> </ul>  Cek link http://127.0.0.1:8000/blog/detail/<your_post_id>
  • 10. Pagination (1)  Use admin interface to make posts  Create template in template/blog/list.html  Add url pattern in blog/url.py so it became like this from django.conf.urls.defaults import * from testsite.blog.models import Post from testsite.blog.views import * urlpatterns = patterns('django.views.generic.date_based', (r'^add', add_blog ), (r'^list/(?P<page>d+)/$', list), (r'^detail/(?P<post_id>d+)/$', detail), )
  • 11. Pagination(2)  To add pagination, edit blog/views.py, first add the following lines from django.core.paginator import Paginator  Next make the list function like this def list(request, page = 1): page = int(page) post_list = Paginator(Post.objects.all(), 5, allow_empty_first_page=True) post_page = post_list.page(page) num = post_page.start_index() count = post_page.end_index() has_previous = post_page.has_previous() has_next = post_page.has_next() return render_to_response( 'blog/list.html', { 'post_list': post_page.object_list, 'has_previous': has_previous, 'previous_page': page - 1, 'has_next': has_next, 'next_page': page + 1, 'page' : page, 'num' : num, 'count' : count } )
  • 12. Pagination (3) create the template  Create In template/blog/list.html, and write the following {% if post_list %} {{ page }} {{ num }} {{ count }} <a href='/blog/add/'> add </a> <ul> {% for post in post_list %} <li><a href='/blog/detail/{{ post.id }}'> {{post.title}}</a></li> {% endfor %} </ul> {% if has_previous %} <a href='/blog/list/{{ previous_page }}'>Previous</a> {% if has_next %} | {% endif %} {% endif %} {% if has_next %} <a href='/blog/list/{{ next_page }}'>Next</a> {% endif %} {% else %} <p>No links found.</p> {% endif %}
  • 13. Check blog/urls.py  Before continuing, please make sure that the urls.py looks like this from django.conf.urls.defaults import * from testsite.blog.models import Post from testsite.blog.views import * urlpatterns = patterns('', (r'^add', add_blog ), (r'^list/(?P<page>d+)/$', list), (r'^detail/(?P<post_id>d+)/$', detail), (r'^update/(?P<post_id>d+)/$', update), (r'^delete/(?P<post_id>d+)/$', delete) )
  • 14. Creating Form Create (1) The Model  In blog/model.py add this #top from django.forms import ModelForm #under class post class PostForm(ModelForm): class Meta: model = Post #the fields on the form, you can add fields, but must corespond with field in Post fields = ('title', 'post')
  • 15. Creating Form Create (2) The View Top  Add this lines #top from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response, get_object_or_404 from django.template.loader import get_template from django.template import Context, loader, RequestContext from testsite.blog.models import * from django.contrib.auth.models import User from datetime import datetime from django.views.decorators.csrf import csrf_protect from django.core.paginator import Paginator
  • 16. Creating Form Create (2) The View Bottom #bottom def add_blog(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form = PostForm(request.POST) blog = form.save(commit=False) blog.author = User.objects.get(id = request.user.id) blog.date = datetime.now() blog.save() return HttpResponseRedirect("/blog/list/1") else: return render_to_response('blog/add_blog.html', {'error': True, 'form': form}) else: return render_to_response('blog/add_blog.html', {'error': True, 'form': form})
  • 17. Creating Form Create (3) The Template <html> <head> <title>blog</title> </head> <body> {% if error %} <p style="color: red;">Please submit a blog.</p> {% endif %} {% csrf_token %} <form action="" method="post"> <table> {{ form.as_table }} </table> <input type="submit" value ="submit"> </form> </body> </html>
  • 18. Creating Form Update (1) The View  Add this code def update(request, post_id): post = Post.objects.get(pk=post_id) if request.method == 'POST': form = PostForm(request.POST, instance=post) if form.is_valid(): form.save() return HttpResponseRedirect("/blog/list/1") else: return render_to_response('blog/add_blog.html', {'error': True, 'form': form}) else: form = PostForm(instance=post) return render_to_response('blog/add_blog.html', {'error': True, 'form': form})
  • 19. Creating Form Update (2) The Template <html> <head> <title>blog</title> </head> <body> {% if error %} <p style="color: red;">Please submit a blog.</p> {% endif %} {% csrf_token %} <form action="" method="post"> <table> {{ form.as_table }} </table> <input type="submit" value ="submit"> </form> </body> </html>
  • 20. Creating Form Delete (1) The View def delete(request, post_id): p = Post.objects.get(pk=post_id) p.delete() return HttpResponseRedirect("/blog/list/1")
  • 21. Misc  You can grab the files in http://wirekom.co.id/uploads/testsite.zip