django python

Django

Installation

Ubuntu

Update :

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

Ref :
https://docs.djangoproject.com/en/dev/ref/contrib/gis/install/#ubuntudebian
https://docs.djangoproject.com/en/dev/topics/install/?from=olddocs#installing-an-official-release

Verifying

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()
1.3

Starting Project

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

django-admin.py startproject mysite

Starting Server

In mysite directory .

sudo python manage.py runserver localhost:8000

Sync Database

python manage.py syncdb

Migrate Database

python manage.py migrate

Importing Data

python manage.py loaddata datadump.json

Dump data

python manage.py dumpdata > rahuldatadump.json

Sql of module

python manage.py sql polls

Adding Field and model to db

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

http://stackoverflow.com/questions/2902800/django-sync-db-question
http://south.aeracode.org/docs/commands.html#schemamigration

Creating Models

python manage.py startapp polls

Site Module

https://docs.djangoproject.com/en/dev/ref/contrib/sites/#example-usage

Signals

https://docs.djangoproject.com/en/dev/topics/signals/

Django shortcut functions

https://docs.djangoproject.com/en/1.2/topics/http/shortcuts/

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 :
https://docs.djangoproject.com/en/dev/ref/contrib/admin/

Implementing User Registration

Ref:
http://www.b-list.org/weblog/2006/sep/02/django-tips-user-registration/
http://code.google.com/p/django-registration/wiki/ReadMe

Django Path in Ubuntu

/usr/local/lib/python2.7/dist-packages/Django-1.3.1-py2.7.egg/

Django Template

ifcondition

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

http://www.djangobook.com/en/1.0/chapter04/

for escape html in template

FILTER: {{ myhtml |safe }}
http://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe
TAG: {% autoescape off %}{{ myhtml }}{% endautoescape %}

http://stackoverflow.com/questions/4848611/django-rendering-a-template-variable-as-html

Django url.py

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

)
urlpatterns += patterns(”,

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

https://docs.djangoproject.com/en/dev/topics/http/urls/

Django Forms

Form.cleaned_data

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’: ‘foo@example.com’,
…        ‘cc_myself’: True}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{‘cc_myself’: True, ‘message’: u’Hi there’, ‘sender’: u’foo@example.com’, ‘subject’: u’hello’}

https://docs.djangoproject.com/en/dev/ref/forms/api/#accessing-clean-data

Ref:
https://docs.djangoproject.com/en/dev/topics/forms/
https://docs.djangoproject.com/en/dev/ref/forms/fields/
https://docs.djangoproject.com/en/dev/ref/forms/widgets/

Query Dict

https://docs.djangoproject.com/en/dev/ref/request-response/#querydict-objects

Django Models

Making queries

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

https://docs.djangoproject.com/en/dev/topics/db/queries/

Model.__unicode__()

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>
{{ form.media }}
<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 %}”;
</script>

Ref :
http://stackoverflow.com/questions/38601/using-django-time-date-widgets-in-custom-form

django password:

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

http://pypi.python.org/pypi/django-passwords/
https://github.com/dstufft/django-passwords/

translation

mkdir localedjango-admin.py makemessages -l es

django-admin.py 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

http://stackoverflow.com/questions/5895716/non-english-character-getting-changed-to-character-in-linux

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

django date time format

print datetime.now().strftime(“%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’):
cd_error=item.text
for item in parsed.findall(‘nb_error’):
nb_error=item.text
for item in parsed.findall(‘response’):
response=item.text
ncServerData=’ ‘+response+’ ‘+cd_error+’ ‘+nb_error

Error Handling

try:
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)
c.perform()
except Exception, e:
print e, repr(e), e.message, e.args

Generate Unique ID:

>>> import uuid
>>> x=uuid.uuid4()
>>> str(x)
‘07033084-5cfd-4812-90a4-e4d24ffb6e3d’

Switch Statement

as function

result = {
‘a’: lambda x: x * 5,
‘b’: lambda x: x + 7,
‘c’: lambda x: x – 2
}[value](x)

normal

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

String Replace

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

http://www.tutorialspoint.com/python/string_replace.htm

Django FTP Upload

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

fp.close() # Close file and FTP
sftp.quit()

http://love-python.blogspot.in/2008/02/ftp-file-upload.html

Make csv

import csv
import sysf = open(‘testcsv.csv’, ‘wt’)
try:
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)) )
finally:
f.close()

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

santandar curl

import pycurl
ncServerURL=’https://dev.mitec.com.mx/wscobroSdos/CobroAirlines&#8217;
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)
c.perform()
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 pycurl_7.xxx.dsc
8.) cd pycurl-7.xxx
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

http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=515200

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

http://www.travisglines.com/web-coding/python-xml-parser-tutorial

http://www.diveintopython.net/xml_processing/attributes.html

django indentaion

python -m tabnanny <name of python file>

http://stackoverflow.com/questions/1016814/what-to-do-with-unexpected-indent-in-python

django Apache

sudo touch apache/django.wsgi

https://code.djangoproject.com/wiki/django_apache_and_mod_wsgi

declaring array

a=[]

Iteration over model instance

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

Ref :

http://stackoverflow.com/questions/2170228/django-iterate-over-model-instance-field-names-and-values-in-template

simple loop

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

http://stackoverflow.com/questions/522563/accessing-the-index-in-python-for-loops

json library

json.dump
json.load

http://docs.python.org/library/json.html

django validation

http://eikke.com/django-validation-an-introduction/

Steps to configure apache with django

1. Create a virtual host entry as below.

<VirtualHost demo.wolfkrow.com:80>
ServerAdmin webmaster@localhost
ServerName demo.wolfkrow.com
DocumentRoot /home/vclub/vclubcms
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<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]
</Directory>
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 :

https://docs.djangoproject.com/en/1.3/intro/tutorial01/
https://docs.djangoproject.com/en/1.3/intro/tutorial02/

Advertisements

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s