Django Simple CRUD
Django Simple CRUD
Django Simple CRUD
7 and mysql
Making Simple Blog
By ivan sugiarto
[email protected]
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)),
)
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
<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