ok today i will tell you how create application in python using django already i have tell you that python easy and smooth and also i have tell you how you install or create a application with mysql in django in previous article:
http://netai-nayek.blogspot.in/2014/08/today-is-my-first-blog-i-dont-know-how.html
http://netai-nayek.blogspot.in/2014/08/how-create-model-in-django.html
http://netai-nayek.blogspot.in/2014/08/how-create-besic-app-in-django.html
http://netai-nayek.blogspot.in/2014/08/how-start-your-first-django-programing.html
http://netai-nayek.blogspot.in/2014/08/how-to-get-database-data-in-django-view.html
http://netai-nayek.blogspot.in/2014/08/how-create-django-template.html
and also i have tell you how you create or login using django default user table:
http://netai-nayek.blogspot.in/2014/08/how-to-create-or-registerlogin-and.html
but i know you know all of this but you have any idie how you will start so today i have decide that i will tell you how you create/design a project , i give a sample project like user todo list, Already i have create this project using node.js but here i will create using python with django i think you will enjoy in this project
ok let's start your sample project:
create a database in mysql like todo
first open your terminal and go to that folder where you want to create your folder and type bellow command:
$ django-admin.py startproject todo
this command create a project todo with a folder structure.
next goto todo folder and type bellow command:
$cd todo
$python manage.py startapp app
$python manage.py startapp data
it will create two app one for web view and other for database connection
and it will create two folder one app and data
ok next edit setting.py and copy bellow all in setting.py file
setting.py
"""
Django settings for store project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import os.path
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^py0denvmw(8&m1i@wi%5-c6_nmk@&!!2)os7pyr#0gr8fc4kv'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)
SITE_ID=1
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'todo.app',
'todo.data'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'store.urls'
WSGI_APPLICATION = 'store.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "todo",
'USER': "root",
'PASSWORD':"root",
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = os.path.join(BASE_DIR, 'todo/static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'todo/media/')
MEDIA_URL = 'static/media/'
next open data folder and edit models.py file and copy bellow syntex:
data/models.py
from django.db import models
from datetime import datetime, timedelta
class User(models.Model):
fname = models.CharField(max_length=255)
lname= models.CharField(max_length=255)
email=models.EmailField(max_length=255)
password = models.CharField(max_length=200)
join_date=models.DateTimeField(editable=False,default=datetime.now())
#profile_pic = models.ImageField(upload_to = 'user/',null=True)
class Todo(models.Model):
todo_job= models.TextField()
user=models.ForeignKey('User')
created_date=models.DateTimeField(editable=False,default=datetime.now())
this model for access database and manipulate data in database
and run bellow command from your root folder in terminal
$python manage.py syncdb
next open app folder and delete views.py file and create views folder folder look like this:
open views folder and create __init__.py file and then create two file home.py and todo.py and copy bellow content:
home.py
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from todo.app.forms import *
from django.template import RequestContext
from django.shortcuts import render_to_response
def main_page(request):
if 'user_id' in request.session:
user_obj=User.objects.filter(id=request.session['user_id'])
todo_obj=Todo.objects.filter(user_id=request.session['user_id'])
data=RequestContext(request,{'fname':request.session['fname'],'user':user_obj,'todo':todo_obj,'a':0})
return render_to_response('home.html',data)
else:
form = SignupForm()
variables = RequestContext(request, {'form': form})
return render_to_response('index.html', variables)
def signup(request):
if request.method=='POST':
form=SignupForm(request.POST)
if form.is_valid():
obj=form.save()
id=obj.id
request.session['user_id']=id
request.session['fname']=form.cleaned_data['fname']
return HttpResponseRedirect('/')
def login(request):
user_obj=User.objects.filter(email=request.POST.get('email'),password=request.POST.get('password'))
if user_obj.count():
print user_obj
request.session['user_id']=user_obj[0].id
request.session['fname']=user_obj[0].fname
return HttpResponseRedirect('/')
def logout(request):
del request.session['user_id']
del request.session['fname']
request.session.modified=True
return HttpResponseRedirect('/')
todo.py
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from todo.app.forms import *
from django.template import RequestContext
from django.shortcuts import render_to_response
def add_todo(request):
if request.method=='POST':
todo_obj=Todo(todo_job=request.POST.get('job'),user_id=request.session['user_id'])
todo_obj.save()
return HttpResponseRedirect('/')
else:
data=RequestContext(request,{'fname':request.session['fname']})
return render_to_response('add_todo.html',data)
def edit_todo(request,todo_id):
if request.method=='POST':
todo_obj=Todo.objects.filter(id=request.POST.get('id')).update(todo_job=request.POST.get('job'))
return HttpResponseRedirect('/')
else:
todo_obj=Todo.objects.filter(id=todo_id)
data=RequestContext(request,{'fname':request.session['fname'],'todo':todo_obj[0]})
return render_to_response('edit_todo.html',data)
def delete_todo(request,todo_id):
Todo.objects.get(id=todo_id).delete()
return HttpResponseRedirect('/')
now create a file forms.py file in app folder and copy bellow content:
forms.py
from django import forms
import re
from django.core.exceptions import ObjectDoesNotExist
from django.forms import ModelForm
from todo.data.models import *
class SignupForm(ModelForm):
class Meta:
model=User
now create templates folder in root folder where have app and data folder
and create bellow 5 html file:
base.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Todo list | {% block title %}{% endblock %}</title>
<style>
.mid{
display:block;
min-height:400px;
width:700px;
}
.small-div{
width:40%;
float:left;
padding:10px;
}
input,label{
display:block;
margin:10px 0;
}
.left{
border-right:1px solid #000;
}
table tr:first-child td{
font-weight:bold;
font-size:20px;
border-bottom:1px solid #000;
}
.footer{
margin-top:50px;
border-top:1px solid #000;
}
</style>
{% block head %}{% endblock %}
</head>
<body>
{% block header %}{% endblock %}
{% block content %}{% endblock %}
<div class="footer">
{% block footer %}{% endblock %}
copyright 2014
</div>
</body>
</html>
home.html
{%extends "base.html" %}
{%block title %}{{fname}}{% endblock %}
{%block content %}
<div class="mid">
<div><img src="./images/profile/thumb/{{pic}}" width="50" style="vertical-align:middle;"> <b>{{fname}}</b> | <a href="/logout">Logout</a></div>
<h1>Todo List</h1>
<a href="add-todo">Add Todo</a>
<table width="100%" cellpadding="5">
<tr>
<td width="20%">Date</td><td width="70%">Job</td><td width="5%"> </td>
</tr>
{%for row in todo%}
<tr><td>{{row.created_date|date:"D d M Y"}}</td><td>{{row.todo_job}}</td><td><a href="/edit-todo/{{row.id}}">Edit</a> | <a href="/delete-todo/{{row.id}}">Delete</a></td></tr>
{%endfor%}
</table>
</div>
{% endblock %}
index.html
{%extends "base.html" %}
{%block title %}Welcome{% endblock %}
{%block content %}
<div class="mid">
<div class="left small-div">
<h1>Signup</h1>
<form action="signup" method="post" enctype="multipart/form-data" id="frmId">
{{form.as_p}}
<input type="submit" value="signup" class="btn">
{%csrf_token%}
</form>
</div>
<div class="right small-div">
<h1>Login</h1>
<form action="login" method="post">
<label>Email</label>
<input type="text" name="email" required>
<label>Password</label>
<input type="password" name="password" required>
<input type="submit" value="Login">
{%csrf_token%}
</form>
</div>
<div style="clear:both;"></div>
</div>
{% endblock %}
add_todo.html
{%extends "base.html"%}
{%block title %}Add | {{fname}}{% endblock %}
{%block content%}
<div class="mid">
<div><b>{{fname}}</b> | <a href="/logout">Logout</a></div>
<h1>Add Todo List</h1>
<form action="add-todo" method="post">
<label>Job</label>
<textarea name="job" required></textarea>
<input type="submit" value="Add">
{%csrf_token%}
</form>
</div>
{% endblock %}
edit_todo.py
{%extends "base.html"%}
{%block title %}Add | {{fname}}{% endblock %}
{%block content%}
<div class="mid">
<div><b>{{fname}}</b> | <a href="/logout">Logout</a></div>
<h1>Add Todo List</h1>
<form action="" method="post">
<label>Job</label>
<textarea name="job" required>{{todo.todo_job}}</textarea>
<input type="hidden" name="id" value="{{todo.id}}">
<input type="submit" value="Add">
{%csrf_token%}
</form>
</div>
{% endblock %}
now edit urls.py file in store folder and copy bellow content:
urls.py
from django.conf.urls import patterns, include, url
from todo.app.views import home
from todo.app.views import todo
from django.contrib import admin
import os.path
admin.autodiscover()
site_media = os.path.join(os.path.dirname(__file__), 'site_media')
urlpatterns = patterns('',url(r'^admin/', include(admin.site.urls)),)
urlpatterns += patterns('',(r'^$', home.main_page),)
urlpatterns += patterns('',(r'^signup$', home.signup),)
urlpatterns += patterns('',(r'^login$', home.login),)
urlpatterns += patterns('',(r'^logout$', home.logout),)
urlpatterns += patterns('',(r'^add-todo$', todo.add_todo),)
urlpatterns += patterns('',(r'^edit-todo/(?P<todo_id>\d+)$', todo.edit_todo),)
urlpatterns += patterns('',(r'^delete-todo/(?P<todo_id>\d+)$', todo.delete_todo),)
now your application have completed now start server type bellow command from store folder where manage.py folder have
$python manage.py runserver
then open localhost:8000 then you can see bellow screen
so now enjoy your new cocktail .
if you get any problem or anything else you comment without any hesitation
http://netai-nayek.blogspot.in/2014/08/today-is-my-first-blog-i-dont-know-how.html
http://netai-nayek.blogspot.in/2014/08/how-create-model-in-django.html
http://netai-nayek.blogspot.in/2014/08/how-create-besic-app-in-django.html
http://netai-nayek.blogspot.in/2014/08/how-start-your-first-django-programing.html
http://netai-nayek.blogspot.in/2014/08/how-to-get-database-data-in-django-view.html
http://netai-nayek.blogspot.in/2014/08/how-create-django-template.html
and also i have tell you how you create or login using django default user table:
http://netai-nayek.blogspot.in/2014/08/how-to-create-or-registerlogin-and.html
but i know you know all of this but you have any idie how you will start so today i have decide that i will tell you how you create/design a project , i give a sample project like user todo list, Already i have create this project using node.js but here i will create using python with django i think you will enjoy in this project
ok let's start your sample project:
create a database in mysql like todo
first open your terminal and go to that folder where you want to create your folder and type bellow command:
$ django-admin.py startproject todo
this command create a project todo with a folder structure.
next goto todo folder and type bellow command:
$cd todo
$python manage.py startapp app
$python manage.py startapp data
it will create two app one for web view and other for database connection
and it will create two folder one app and data
ok next edit setting.py and copy bellow all in setting.py file
setting.py
"""
Django settings for store project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import os.path
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '^py0denvmw(8&m1i@wi%5-c6_nmk@&!!2)os7pyr#0gr8fc4kv'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)
SITE_ID=1
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'todo.app',
'todo.data'
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'store.urls'
WSGI_APPLICATION = 'store.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': "todo",
'USER': "root",
'PASSWORD':"root",
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = os.path.join(BASE_DIR, 'todo/static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'todo/media/')
MEDIA_URL = 'static/media/'
next open data folder and edit models.py file and copy bellow syntex:
data/models.py
from django.db import models
from datetime import datetime, timedelta
class User(models.Model):
fname = models.CharField(max_length=255)
lname= models.CharField(max_length=255)
email=models.EmailField(max_length=255)
password = models.CharField(max_length=200)
join_date=models.DateTimeField(editable=False,default=datetime.now())
#profile_pic = models.ImageField(upload_to = 'user/',null=True)
class Todo(models.Model):
todo_job= models.TextField()
user=models.ForeignKey('User')
created_date=models.DateTimeField(editable=False,default=datetime.now())
this model for access database and manipulate data in database
and run bellow command from your root folder in terminal
$python manage.py syncdb
next open app folder and delete views.py file and create views folder folder look like this:
open views folder and create __init__.py file and then create two file home.py and todo.py and copy bellow content:
home.py
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from todo.app.forms import *
from django.template import RequestContext
from django.shortcuts import render_to_response
def main_page(request):
if 'user_id' in request.session:
user_obj=User.objects.filter(id=request.session['user_id'])
todo_obj=Todo.objects.filter(user_id=request.session['user_id'])
data=RequestContext(request,{'fname':request.session['fname'],'user':user_obj,'todo':todo_obj,'a':0})
return render_to_response('home.html',data)
else:
form = SignupForm()
variables = RequestContext(request, {'form': form})
return render_to_response('index.html', variables)
def signup(request):
if request.method=='POST':
form=SignupForm(request.POST)
if form.is_valid():
obj=form.save()
id=obj.id
request.session['user_id']=id
request.session['fname']=form.cleaned_data['fname']
return HttpResponseRedirect('/')
def login(request):
user_obj=User.objects.filter(email=request.POST.get('email'),password=request.POST.get('password'))
if user_obj.count():
print user_obj
request.session['user_id']=user_obj[0].id
request.session['fname']=user_obj[0].fname
return HttpResponseRedirect('/')
def logout(request):
del request.session['user_id']
del request.session['fname']
request.session.modified=True
return HttpResponseRedirect('/')
todo.py
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponseRedirect
from django.contrib.auth import logout
from todo.app.forms import *
from django.template import RequestContext
from django.shortcuts import render_to_response
def add_todo(request):
if request.method=='POST':
todo_obj=Todo(todo_job=request.POST.get('job'),user_id=request.session['user_id'])
todo_obj.save()
return HttpResponseRedirect('/')
else:
data=RequestContext(request,{'fname':request.session['fname']})
return render_to_response('add_todo.html',data)
def edit_todo(request,todo_id):
if request.method=='POST':
todo_obj=Todo.objects.filter(id=request.POST.get('id')).update(todo_job=request.POST.get('job'))
return HttpResponseRedirect('/')
else:
todo_obj=Todo.objects.filter(id=todo_id)
data=RequestContext(request,{'fname':request.session['fname'],'todo':todo_obj[0]})
return render_to_response('edit_todo.html',data)
def delete_todo(request,todo_id):
Todo.objects.get(id=todo_id).delete()
return HttpResponseRedirect('/')
now create a file forms.py file in app folder and copy bellow content:
forms.py
from django import forms
import re
from django.core.exceptions import ObjectDoesNotExist
from django.forms import ModelForm
from todo.data.models import *
class SignupForm(ModelForm):
class Meta:
model=User
now create templates folder in root folder where have app and data folder
and create bellow 5 html file:
base.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Todo list | {% block title %}{% endblock %}</title>
<style>
.mid{
display:block;
min-height:400px;
width:700px;
}
.small-div{
width:40%;
float:left;
padding:10px;
}
input,label{
display:block;
margin:10px 0;
}
.left{
border-right:1px solid #000;
}
table tr:first-child td{
font-weight:bold;
font-size:20px;
border-bottom:1px solid #000;
}
.footer{
margin-top:50px;
border-top:1px solid #000;
}
</style>
{% block head %}{% endblock %}
</head>
<body>
{% block header %}{% endblock %}
{% block content %}{% endblock %}
<div class="footer">
{% block footer %}{% endblock %}
copyright 2014
</div>
</body>
</html>
home.html
{%extends "base.html" %}
{%block title %}{{fname}}{% endblock %}
{%block content %}
<div class="mid">
<div><img src="./images/profile/thumb/{{pic}}" width="50" style="vertical-align:middle;"> <b>{{fname}}</b> | <a href="/logout">Logout</a></div>
<h1>Todo List</h1>
<a href="add-todo">Add Todo</a>
<table width="100%" cellpadding="5">
<tr>
<td width="20%">Date</td><td width="70%">Job</td><td width="5%"> </td>
</tr>
{%for row in todo%}
<tr><td>{{row.created_date|date:"D d M Y"}}</td><td>{{row.todo_job}}</td><td><a href="/edit-todo/{{row.id}}">Edit</a> | <a href="/delete-todo/{{row.id}}">Delete</a></td></tr>
{%endfor%}
</table>
</div>
{% endblock %}
index.html
{%extends "base.html" %}
{%block title %}Welcome{% endblock %}
{%block content %}
<div class="mid">
<div class="left small-div">
<h1>Signup</h1>
<form action="signup" method="post" enctype="multipart/form-data" id="frmId">
{{form.as_p}}
<input type="submit" value="signup" class="btn">
{%csrf_token%}
</form>
</div>
<div class="right small-div">
<h1>Login</h1>
<form action="login" method="post">
<label>Email</label>
<input type="text" name="email" required>
<label>Password</label>
<input type="password" name="password" required>
<input type="submit" value="Login">
{%csrf_token%}
</form>
</div>
<div style="clear:both;"></div>
</div>
{% endblock %}
add_todo.html
{%extends "base.html"%}
{%block title %}Add | {{fname}}{% endblock %}
{%block content%}
<div class="mid">
<div><b>{{fname}}</b> | <a href="/logout">Logout</a></div>
<h1>Add Todo List</h1>
<form action="add-todo" method="post">
<label>Job</label>
<textarea name="job" required></textarea>
<input type="submit" value="Add">
{%csrf_token%}
</form>
</div>
{% endblock %}
edit_todo.py
{%extends "base.html"%}
{%block title %}Add | {{fname}}{% endblock %}
{%block content%}
<div class="mid">
<div><b>{{fname}}</b> | <a href="/logout">Logout</a></div>
<h1>Add Todo List</h1>
<form action="" method="post">
<label>Job</label>
<textarea name="job" required>{{todo.todo_job}}</textarea>
<input type="hidden" name="id" value="{{todo.id}}">
<input type="submit" value="Add">
{%csrf_token%}
</form>
</div>
{% endblock %}
now edit urls.py file in store folder and copy bellow content:
urls.py
from django.conf.urls import patterns, include, url
from todo.app.views import home
from todo.app.views import todo
from django.contrib import admin
import os.path
admin.autodiscover()
site_media = os.path.join(os.path.dirname(__file__), 'site_media')
urlpatterns = patterns('',url(r'^admin/', include(admin.site.urls)),)
urlpatterns += patterns('',(r'^$', home.main_page),)
urlpatterns += patterns('',(r'^signup$', home.signup),)
urlpatterns += patterns('',(r'^login$', home.login),)
urlpatterns += patterns('',(r'^logout$', home.logout),)
urlpatterns += patterns('',(r'^add-todo$', todo.add_todo),)
urlpatterns += patterns('',(r'^edit-todo/(?P<todo_id>\d+)$', todo.edit_todo),)
urlpatterns += patterns('',(r'^delete-todo/(?P<todo_id>\d+)$', todo.delete_todo),)
now your application have completed now start server type bellow command from store folder where manage.py folder have
$python manage.py runserver
then open localhost:8000 then you can see bellow screen
so now enjoy your new cocktail .
if you get any problem or anything else you comment without any hesitation