django python




Update :

sudo apt-get update
sudo apt-get install binutils gdal-bin libproj-dev  python-psycopg2 python-setuptools python-mysqldbsudo easy_install Django

Ref :


To verify that Django can be seen by Python, type python from your shell. Then at the Python prompt, try to import Django:

python –version
>>> import django
>>> print django.get_version()

Starting Project

From the command line, cd into a directory where you’d like to store your code, then run the following command: startproject mysite

Starting Server

In mysite directory .

sudo python runserver localhost:8000

Sync Database

python syncdb

Migrate Database

python migrate

Importing Data

python loaddata datadump.json

Dump data

python dumpdata > rahuldatadump.json

Sql of module

python sql polls

Adding Field and model to db

python schemamigration member–add-field Profile.type
python schemamigration member–add-model Member
python schemamigration member –add-model OnwardJourneypython migrate member

Creating Models

python startapp polls

Site Module


Django shortcut functions

Django Admin

One of the most powerful parts of Django is the automatic admin interface. It reads metadata in your model to provide a powerful and production-ready interface that content producers can immediately use to start adding content to the site. In this document, we discuss how to activate, use and customize Django’s admin interface.

Reference :

Implementing User Registration


Django Path in Ubuntu


Django Template


{% ifnotequal user “AnonymousUser” %}
{{ user }}
<a href=”/accounts/logout”>Logout</a>
{% else %}
<a href=”/accounts/login”>Login</a>
{% endifnotequal  %}

for escape html in template

FILTER: {{ myhtml |safe }}
TAG: {% autoescape off %}{{ myhtml }}{% endautoescape %}


patterns(prefix, pattern_description, …)urlpatterns = patterns(”,

urlpatterns += patterns(”,

url(regex, view, kwargs=None, name=None, prefix=”)
url(r’^index/$’, index_view, name=”main-view”),

Django Forms


Each field in a Form class is responsible not only for validating data, but also for “cleaning” it — normalizing it to a consistent format. This is a nice feature, because it allows data for a particular field to be input in a variety of ways, always resulting in consistent output.

>>> data = {‘subject’: ‘hello’,
…        ‘message’: ‘Hi there’,
…        ‘sender’: ‘’,
…        ‘cc_myself’: True}
>>> f = ContactForm(data)
>>> f.is_valid()
>>> f.cleaned_data
{‘cc_myself’: True, ‘message’: u’Hi there’, ‘sender’: u’’, ‘subject’: u’hello’}


Query Dict

Django Models

Making queries

all_entries = Entry.objects.all()Entry.objects.filter(pub_date__year=2006)


he __unicode__() method is called whenever you call unicode() on an object. Django uses unicode(obj) (or the related function, str(obj)) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object. Thus, you should always return a nice, human-readable representation of the model from the __unicode__() method.

class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)def __unicode__(self):
return u’%s %s’ % (self.first_name, self.last_name)

Adding Admin date widget in frontend

{% load adminmedia %} <!–at top –>
<script type=”text/javascript” src=”/admin/jsi18n/”></script>
<script type=”text/javascript” src=”/static/admin/js/core.js”></script>
<link rel=”stylesheet” type=”text/css” href=”/static/admin/css/forms.css”/>
<link rel=”stylesheet” type=”text/css” href=”/static/admin/css/widgets.css”/>
<script type=”text/javascript” src=”/media/js/slides.min.jquery.js”></script>
{{ }}
<link rel=”stylesheet” type=”text/css” href=”/static/admin/css/base.css”/>
<link rel=”stylesheet” type=”text/css” href=”/static/admin/css/global.css”/>
<script type=”text/javascript”>
window.__admin_media_prefix__ = “{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}”;

Ref :

django password:

path : /usr/local/lib/python2.7/dist-packages/passwords


mkdir makemessages -l es compilemessages

locale/de/LC_MESSAGES/django.po:472:70: invalid multibyte sequence

file -i django.po
iconv –from-code=ISO-8859-1 –to-code=UTF-8 django.po > django_utf8.po

Will not show message if some fuzzy word in .po file

django date time format

print“%Y/%m/%d %H:%M:%S”)

django xml parse by string

from xml.etree.ElementTree import XML, fromstring, tostring
parsed = fromstring(ncServerData)
print ‘parsed’
# print parsed.attr(‘cd_error’)
for item in parsed.findall(‘cd_error’):
for item in parsed.findall(‘nb_error’):
for item in parsed.findall(‘response’):
ncServerData=’ ‘+response+’ ‘+cd_error+’ ‘+nb_error

Error Handling

c = pycurl.Curl()
c.setopt(pycurl.URL, ncServerURL)
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, “xml=”+str(body))
import StringIO
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
except Exception, e:
print e, repr(e), e.message, e.args

Generate Unique ID:

>>> import uuid
>>> x=uuid.uuid4()
>>> str(x)

Switch Statement

as function

result = {
‘a’: lambda x: x * 5,
‘b’: lambda x: x + 7,
‘c’: lambda x: x – 2


def f(x):
return {
‘a’: 1,
‘b’: 2,

String Replace

str = “this is string example….wow!!! this is really string”;
print str.replace(“is”, “was”);
print str.replace(“is”, “was”, 3);

Django FTP Upload

import ftplibsftp = ftplib.FTP(‘’,’cognisys’,’bij897jib’) # Connect
fp = open(‘’,’rb’) # file to send
sftp.storbinary(‘STOR volaris/’, fp) # Send the file

fp.close() # Close file and FTP

Make csv

import csv
import sysf = open(‘testcsv.csv’, ‘wt’)
writer = csv.writer(f)
writer.writerow( (‘Title 1’, ‘Title 2’, ‘Title 3’) )
for i in range(10):
writer.writerow( (i+1, chr(ord(‘a’) + i), ’08/%02d/07′ % (i+1)) )

print open(‘testcsv.csv’, ‘rt’).read()

santandar curl

import pycurl
binaryptr = open(‘sample.xml’,’rb’).read()
c = pycurl.Curl()
c.setopt(pycurl.URL, ncServerURL)
c.setopt(pycurl.POST, 1)c.setopt(pycurl.NOSIGNAL, 1) # disable signals, curl will be using other means besides signals to timeout.
c.setopt(pycurl.POSTFIELDS, “xml=”+binaryptr)
import StringIO
b = StringIO.StringIO()
c.setopt(pycurl.WRITEFUNCTION, b.write)
ncServerData = b.getvalue()
print ncServerData

Pycurl working with open ssl

I figured I’d post a workaround for people to fix the python-pycurl
package themselves.1.) sudo apt-get install build-essential fakeroot dpkg-dev
2.) mkdir ~/python-pycurl-openssl
3.) cd ~/python-pycurl-openssl
4.) sudo apt-get source python-pycurl
5.) sudo apt-get build-dep python-pycurl
6.) sudo apt-get install libcurl4-openssl-dev
7.) sudo dpkg-source -x
8.) cd
9.) Edit the debian/control file and replace all instances of
“libcurl4-gnutls-dev” with “libcurl4-openssl-dev”
10.) sudo dpkg-buildpackage -rfakeroot -b
11.) sudo dpkg -i ../python-pycurl_7.xxxx_i386.deb

XML Dom Parser

parsed = parseString(resp_avail)
xmlTag = parsed.getElementsByTagName(‘DepartureAirport’)[0].toxml()
xmlTag1 = parsed.getElementsByTagName(‘DepartureAirport’)[1].toxml()
# xmlData=xmlTag.replace(‘<DepartureAirport>’,”).replace(‘</DepartureAirport>’,”)
print parsed.getElementsByTagName(‘DepartureAirport’)[0].attributes[“LocationCode”].value

django indentaion

python -m tabnanny <name of python file>

django Apache

sudo touch apache/django.wsgi

declaring array


Iteration over model instance

from django.core import serializers
data = serializers.serialize( “python”, SomeModel.objects.all() )

Ref :

simple loop

for idx, val in enumerate(ints):
print idx, val

json library


django validation

Steps to configure apache with django

1. Create a virtual host entry as below.

ServerAdmin webmaster@localhost
DocumentRoot /home/vclub/vclubcms
<Directory />
Options FollowSymLinks
AllowOverride None
<Directory /home/vclub/vclubcms/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/en/(.*)$ /$1 [R]
RewriteRule ^/es/(.*)$ /$1 [R]
WSGIDaemonProcess vclubcms processes=2 threads=15 display-name=%{GROUP}
WSGIProcessGroup vclubcms
WSGIScriptAlias / /home/vclub/vclubcms/apache/django.wsgi</VirtualHost>

2. Create apache/django.wsgi in your codebase with content as follows:

import os
import syspath = ‘/home/vclub’
if path not in sys.path:
sys.path.insert(0, ‘/home/vclub’)

os.environ[‘DJANGO_SETTINGS_MODULE’] = ‘vclubcms.settings’

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

3. Restart Apache

Note: This assumes the basepath is /home/vclub and codebase is in /home/vclub/vclubcms

References :


About rahul23134654

Hi, I am Rahul Meha , B.E. in (I.T.)
This entry was posted in django python. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s