Custom Search

Wednesday, March 31, 2010

environment variable DJANGO_SETTINGS_MODULE is undefined

solution to environment variable DJANGO_SETTINGS_MODULE is undefined

If you're playng with Django directly from Python, and not from Django's own manage.py shell, then you need to set the DJANGO_SETTINGS_MODULE variable before launching Python.

For example, if you have a Django project named "myproject", then run the following before launching Python:

export DJANGO_SETTINGS_MODULE=myproject.settings

For Apache to pick up that variable, you need to set it in httpd.conf as follows:

SetEnv DJANGO_SETTINGS_MODULE myproject.settings

Example:
saju@saju-pardus ~ $ export DJANGO_SETTINGS_MODULE=myproject.settings
saju@saju-pardus ~ $ echo $DJANGO_SETTINGS_MODULE
myproject.settings

Tuesday, March 30, 2010

Full Text Search engine for Django projects

Full Text Search engine for Django projects

http://code.google.com/p/django-fts/

To install the latest version:
http://django-fts.googlecode.com/svn/trunk/

To install the latest version:

svn checkout http://django-fts.googlecode.com/svn/trunk/ django-fts
cd django
-fts
python setup
.py install

------------------------

AttributeError: 'NoneType' object has no attribute 'column'

Solution:

http://code.google.com/p/django-fts/issues/detail?id=5#c2

As a short-term fix, I removed `objects = fts.SearchManager()` from backends.SearchableModel, then added the
appropriate objects definition directly on my model, in the same way the docs tell you to if you want to define
which fields should be indexed.


**********************

Popular Full Text Search engine projects

1) haystack

2) django-sphinx


**********************

python postgresql migration script example two

python postgresql migration script example two

# -*- coding: utf-8 -*-

import sys
import psycopg2
#from migrate_users import *


pgsql_source_connection = None
pgsql_source_cursor = None
Publish Post

pgsql_source_queries = 0


# Gets the PostgreSQL Source credentials
def get_pg_source_credentials():
c = {}
c['host'] = 'localhost'
c['database'] = 'olddb1'
c['user'] = 'kane'
c['password'] = 'xxx'
c['port'] = '5432'
return c





# Opens a connection to the Source PostgreSQL database
def get_pgsql_source_connection():
try:
credentials = get_pg_source_credentials()
conn = psycopg2.connect("dbname='" + credentials['database'] + "' " + \
"user='" + credentials['user'] + "' " + \
"host='" + credentials['host'] + "' " + \
"port='" + credentials['port'] + "' " + \
"password='" + credentials['password'] + "'")
print "connected to Source db"
except Exception, e:
print "I am unable to connect to the Source PostgreSQL database"
raise e
return conn


def copy_data():
#ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;
#ALTER TABLE products ALTER COLUMN price DROP DEFAULT;

# -------- #

alt_message_number = "alter table siren_message add column message_number integer NOT NULL;"
alt_milestone_number = "alter table siren_milestone add column milestone_number integer NOT NULL DEFAULT 0;"
alt_todolist_number = "alter table siren_todolist add column todolist_number integer NOT NULL DEFAULT 0;"
alt_note_number = "alter table siren_note add column note_number integer NOT NULL DEFAULT 0;"
alt_mockupset_number = "alter table siren_mockupset add column mockupset_number integer NOT NULL;"
alt_category_number = "alter table siren_category add column category_number integer NOT NULL DEFAULT 0;"


alt_ticket_number = "ALTER TABLE siren_ticket ALTER COLUMN ticket_number SET NOT NULL;"


pgsql_source_connection = get_pgsql_source_connection()
pgsql_source_cursor = pgsql_source_connection.cursor()

c = pgsql_source_connection.cursor()
c.execute('begin;')

c.execute(alt_message_number)
c.execute(alt_milestone_number)
c.execute(alt_todolist_number)
c.execute(alt_note_number)
c.execute(alt_mockupset_number)
c.execute(alt_category_number)

c.execute(alt_ticket_number)

c.execute('select * from siren_project;')
for project in list(c.fetchall()):
c.execute('select * from siren_milestone where project_id='+str(project[0])+';')
m = {}
for milestone in list(c.fetchall()):
print milestone[9]
if milestone[9] not in m:
m[milestone[9]] = 1
#print milestone[milestone[9]]
c.execute('update siren_milestone set milestone_number = %d where id = %d' %(m[milestone[9]], milestone[0]))
m[milestone[9]] = m[milestone[9]] + 1
#print m[milestone[9]]
print m


c.execute('select * from siren_project;')
for project in list(c.fetchall()):
c.execute('select * from siren_todolist where project_id='+str(project[0])+';')
t = {}
for todolist in list(c.fetchall()):
print todolist[9]
if todolist[9] not in t:
t[todolist[9]] = 1
c.execute('update siren_todolist set todolist_number = %d where id = %d' %(t[todolist[9]], todolist[0]))
t[todolist[9]] = t[todolist[9]] + 1
print t


c.execute('select * from siren_project;')
for project in list(c.fetchall()):
c.execute('select * from siren_note where project_id='+str(project[0])+';')
n = {}
for note in list(c.fetchall()):
print note[8]
if note[8] not in n:
n[note[8]] = 1
c.execute('update siren_note set note_number = %d where id = %d' %(n[note[8]], note[0]))
n[note[8]] = n[note[8]] + 1
print n


c.execute('select * from siren_project;')
for project in list(c.fetchall()):
c.execute('select * from siren_category where project_id='+str(project[0])+';')
cat = {}
for category in list(c.fetchall()):
print category[5]
if category[5] not in cat:
cat[category[5]] = 1
c.execute('update siren_category set category_number = %d where id = %d' %(cat[category[5]], category[0]))
cat[category[5]] = cat[category[5]] + 1
print cat


alt_milestone_number_drop = "alter table siren_milestone ALTER column milestone_number DROP DEFAULT;"
alt_todolist_number_drop = "alter table siren_todolist ALTER column todolist_number DROP DEFAULT;"
alt_note_number_drop = "alter table siren_note ALTER column note_number DROP DEFAULT;"
alt_category_number_drop = "alter table siren_category ALTER column category_number DROP DEFAULT;"

c.execute(alt_milestone_number_drop)
c.execute(alt_todolist_number_drop)
c.execute(alt_note_number_drop)
c.execute(alt_category_number_drop)

c.execute('commit;')
c.close()



def main():
copy_data()
#print "PostgreSQL queries: {0}".format(pgsql_queries)


if __name__ == "__main__":
main()

-------------------------------------------------

python postgresql migration script example one

python postgresql migration script example one

# -*- coding: utf-8 -*-
import sys
import psycopg2
#from migrate_users import *


pgsql_source_connection = None
pgsql_source_cursor = None
pgsql_source_queries = 0


# Gets the PostgreSQL Source credentials
def get_pg_source_credentials():
c = {}
c['host'] = 'localhost'
c['database'] = 'olddb1'
c['user'] = 'kane'
c['password'] = 'xxx'
c['port'] = '5432'
return c





# Opens a connection to the Source PostgreSQL database
def get_pgsql_source_connection():
try:
credentials = get_pg_source_credentials()
conn = psycopg2.connect("dbname='" + credentials['database'] + "' " + \
"user='" + credentials['user'] + "' " + \
"host='" + credentials['host'] + "' " + \
"port='" + credentials['port'] + "' " + \
"password='" + credentials['password'] + "'")
print "connected to Source db"
except Exception, e:
print "I am unable to connect to the Source PostgreSQL database"
raise e
return conn


def copy_data():

# add column #
alt_todo = "alter table siren_todo add column ticket_id integer;"
alt_ticket = "alter table siren_ticket add column ticket_number integer;"
alt_event = "alter table siren_event add column item_id integer;"
alt_project = "alter table siren_project drop column is_dispaly;"
alt_project_repo = "alter table siren_project drop column code_repository_id;"

#alt_message_number = "alter table siren_message add column message_number integer NOT NULL;"
#alt_milestone_number = "alter table siren_milestone add column milestone_number integer;"
#alt_todolist_number = "alter table siren_todolist add column todolist_number integer;"
#alt_note_number = "alter table siren_note add column note_number integer NOT NULL;"
#alt_mockupset_number = "alter table siren_mockupset add column mockupset_number integer NOT NULL;"
#alt_category_number = "alter table siren_category add column category_number integer NOT NULL;"

pgsql_source_connection = get_pgsql_source_connection()
pgsql_source_cursor = pgsql_source_connection.cursor()

c = pgsql_source_connection.cursor()
c.execute('begin;')
c.execute(alt_todo)
c.execute(alt_ticket)
c.execute(alt_event)
c.execute(alt_project)
c.execute(alt_project_repo)

#c.execute(alt_message_number)
#c.execute(alt_milestone_number)
#c.execute(alt_todolist_number)
#c.execute(alt_note_number)
#c.execute(alt_mockupset_number)
#c.execute(alt_category_number)


c.execute('select * from siren_ticket order by created_on;')
tickets = {}
for ticket in list(c.fetchall()):
if ticket[8] not in tickets:
tickets[ticket[8]] = 1
#print tickets[ticket[8]]
c.execute('update siren_ticket set ticket_number = %d where id = %d' %(tickets[ticket[8]], ticket[0]))
tickets[ticket[8]] = tickets[ticket[8]] + 1
print tickets[ticket[8]]
print tickets


c.execute("update siren_event set type='TK' where type='TKC'")


c.execute("select * from siren_event where type='TK'")
for event in list(c.fetchall()):
e = event[7].split('/')
#print e[5]
c.execute('select ticket_number, title, project_id from siren_ticket where id=%s' %(e[5]))
for t in list(c.fetchall()):
print t[1]
c.execute('select name from siren_project where id=%s' %(t[2]))
for p in list(c.fetchall()):
print p[0]

c.execute("update siren_event set description = '#%s %s (%s)', action='U' where type='TK' and description='Comment:' and url='/siren/projects/1/tickets/%s/'" %(e[5], t[1], p[0], e[5]))
c.execute("update siren_event set description = '#%s %s (%s)' where type='TK' and action='A' and url='/siren/projects/1/tickets/%s/'" %(e[5], t[1], p[0], e[5]))

c.execute("update siren_event set description = '#%s %s (%s)', action='U' where type='TK' and description='Comment:' and url='/siren/projects/4/tickets/%s/'" %(e[5], t[1], p[0], e[5]))
c.execute("update siren_event set description = '#%s %s (%s)' where type='TK' and action='A' and url='/siren/projects/4/tickets/%s/'" %(e[5], t[1], p[0] ,e[5]))

#--------------#

c.execute('CREATE TABLE "siren_projectrepository" (\
"id" serial NOT NULL PRIMARY KEY,\
"code_repository_id" integer NOT NULL REFERENCES "django_vcs_coderepository" ("id") DEFERRABLE INITIALLY DEFERRED,\
"project_id" integer NOT NULL REFERENCES "siren_project" ("id") DEFERRABLE INITIALLY DEFERRED\
)')




c.execute('commit;')
c.close()



def main():
copy_data()
#print "PostgreSQL queries: {0}".format(pgsql_queries)


if __name__ == "__main__":
main()
-------------------------------------------------

How add 'read more...' link using django template filter truncatewords

How add 'read more...' link using django template filter truncatewords

I want to add a read more link if description contain more than 20 words
I am using filter truncatewords:20
I also want to hide read more... link , if words less than 20

solution:

{% ifnotequal foo foo|truncatewords:20 %}
<a href="...">Read more</a>
{% endifnoteuqal %}

The advantage this solution has is it works with truncatewords_html as well.

Example:

<p>
{{ note.description|linebreaks|safe|truncatewords:20 }}
{% ifnotequal note.description note.description|truncatewords:20 %}
<a class="readmore" href="{% url note_detail project.id note.id %}">read more...</a>
{%endifnotequal%}
</p>


------------

You can use the wordcount filter instead

-----------

Saturday, March 27, 2010

how get all days in a month in matrix form python

how get all days in a month in matrix form python

----------------------

import calendar
calendar.setfirstweekday(calendar.SUNDAY) # to set week beginning to Sunday, by default it is Monday
days = calendar.monthcalendar(2010, 2)
print days

---------------------

calendar.monthcalendar(year, month)

Returns a matrix representing a month’s calendar.
Each row represents a week; days outside of the month a represented by zeros.
Each week begins with Monday unless set by setfirstweekday().

---------------------
calendar.setfirstweekday(weekday)

Sets the weekday (0 is Monday, 6 is Sunday) to start each week.
The values MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are provided for convenience.
For example, to set the first weekday to Sunday:

import calendar
calendar.setfirstweekday(calendar.SUNDAY)

---------------------
For more details
http://docs.python.org/library/calendar.html

---------------------

Friday, March 26, 2010

How find last day of a month in python

How find last day of a month in python
How find first and last date of a month in python

>>> import calendar
>>> import datetime
>>> calendar.mdays[datetime.date.today().month]
31
----------------------------------
date = datetime.date.today()
start_date = datetime.datetime(date.year, date.month, 1)
end_date = datetime.datetime(date.year, date.month, calendar.mdays[date.month])

----------------------------------

how to django calendar using template tag

django calendar using template tag
current date highlighted in the calendar
python calendar

------------------------- in template

{% milestone_calendar value late_milestones milestones %}
{{ value }}

------------------------- in css
.calendar {
font-size: 10px;
}

.calendar th {
color: #555555;
background: #DCDCDC;
border-bottom: 1px solid #CCCCCC;
}

.calendar td.today {
background: #99CCFF;
}

.calendar td.weekend {
color: #C3BEBE;
}

.calendar td.late {
background: #339933;
}

.calendar td.future {
background: #FFCC00;
}

.calendar td.future_today {
background: #FFCC00;
color: #6699CC;
}
------------------------- template tag

class MilestoneCalendarNode(template.Node):
def __init__(self ,tag_name, value, late_milestones, upcoming_milestones):
self.late_milestones = late_milestones
self.upcoming_milestones = upcoming_milestones
self.value = value
self.tag_name = tag_name

def render(self, context):
late_milestones = template.resolve_variable(self.late_milestones, context)
upcoming_milestones = template.resolve_variable(self.upcoming_milestones, context)

current_year = datetime.datetime.now().year
current_day = datetime.datetime.now().day
current_month = datetime.datetime.now().month
current_month_name = datetime.datetime.now().strftime("%B")

current_month_late_days = []
current_month_upcoming_days = []

for l in late_milestones:
due_date_month = l.due_date.month
due_date_year= l.due_date.year
if due_date_year == current_year and due_date_month == current_month:
current_month_late_days.append(l.due_date.day)

#print "ldayy", current_month_late_days

for u in upcoming_milestones:
due_date_month = u.due_date.month
due_date_year= u.due_date.year
if due_date_year == current_year and due_date_month == current_month:
current_month_upcoming_days.append(u.due_date.day)

#print "udayy", current_month_upcoming_days

days = calendar.monthcalendar(current_year,current_month)
table_start = "<table class='calendar'><tr><th>"+ current_month_name +":</th><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>"
table_end = "</table>"
for d in days:
table_start = table_start + "<tr><td></td>"
for x in d:
cls = ""
#print "index", d.index(x)
if x == current_day:
cls = "class=today"
elif d.index(x) == 0 or d.index(x) == 6:
cls = "class=weekend"
if x == 0:
x = ''
if x in current_month_late_days:
cls = "class=late"
if x in current_month_upcoming_days:
print "cccc1", cls
if cls:
cls = "class=future_today"
else:
cls = "class=future"
print "cccc2", cls

table_start = table_start + "<td " + cls + ">" + str(x) + "</td>"
table_start = table_start+"</tr>"
table = table_start + table_end

context[self.value] = mark_safe(table)
return ''


@register.tag
def milestone_calendar(parser, token):
try:
tag_name, value, late_milestones, upcoming_milestones = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError
return MilestoneCalendarNode(tag_name, value, late_milestones, upcoming_milestones)

------------------------------

How find future month and year in python

************************************

http://labix.org/python-dateutil#head-ba5ffd4df8111d1b83fc194b97ebecf837add454

today + relativedelta(months=1)


************************************

def next_month(self, date):
month = date.month+1
year = date.year
if month > 12:
month = 1
year = date.year+1
return datetime.datetime(year, month, 1)


************************************


today = datetime.date.today()
next_first_date = today + datetime.timedelta(today.day)
next_second_date = next_first_date + datetime.timedelta(today.day)
next_third_date = next_second_date + datetime.timedelta(today.day)
print "third", next_third_date
print "second", next_second_date
print "next_first_date", next_first_date

next_first_month = next_first_date.month
next_first_year = next_first_date.year
next_first_month_name = next_first_date.strftime("%b")

next_second_month = next_second_date.month
next_second_year = next_second_date.year
next_second_month_name = next_second_date.strftime("%b")

next_third_month = next_third_date.month
next_third_year = next_third_date.year
next_third_month_name = next_third_date.strftime("%b")

How find previous or past month and year in python

How find previous or past month and year in python
----------------------------------
today = datetime.date.today()
past_date = today - datetime.timedelta(today.day)
print "past_date", past_date
---------------------------------
today = datetime.date.today()
lastmonth = today - datetime.timedelta(today.day)
print "last_month", lastmonth

---------------------------------
today = datetime.date.today()
lastmonth = today - datetime.timedelta(today.day + 1)
print "last_month", lastmonth
----------------------------------

Wednesday, March 24, 2010

introduction to psycopg

Python-PostgreSQL Database Adapter

psycopg is a PostgreSQL database adapter for the Python programming language. It was written from scratch with the aim of being very small and fast, and stable as a rock. The main advantages of psycopg are that it supports the full Python DBAPI-2.0, being thread safe at level 2 and providing some very usefull extensions like the user-defined type casters.

psycopg is different from the other database adapter because it was designed for heavily multi-threaded applications that create and destroy lots of cursors and make a conspicuous number of concurrent INSERTs or UPDATEs. Every open Python connection keeps a pool of real (UNIX or TCP/IP) connections to the database. Every time a new cursor is created, a new connection does not need to be opened; instead one of the unused connections from the pool is used. That makes psycopg very fast in typical client-server applications that create a servicing thread every time a client request arrives.

Fetch all rows after query
-------------------------------------
import psycopg
dbh = psycopg.connect('dbname=dbname user=username')
print "Connection successful."

cur = dbh.cursor()
cur.execute("SELECT * FROM myTable")

rows = cur.fetchall()
for row in rows:
print row

dbh.close()

-------------------------------









Thursday, March 18, 2010

python django datetime guide

Introduction

#-----------------------------
#introduction
# There are three common ways of manipulating dates in Python
# mxDateTime - a popular third-party module (not discussed here)
# time - a fairly low-level standard library module
# datetime - a new library module for Python 2.3 and used for most of these samples
# (I will use full names to show which module they are in, but you can also use
# from datetime import datetime, timedelta and so on for convenience)

import time
import datetime

print "Today is day", time.localtime()[7], "of the current year"
# Today is day 218 of the current year

today = datetime.date.today()
print "Today is day", today.timetuple()[7], "of ", today.year
# Today is day 218 of 2003

print "Today is day", today.strftime("%j"), "of the current year"
# Today is day 218 of the current year


Finding Today's Date

#-----------------------------
# Finding todays date

today = datetime.date.today()
print "The date is", today
#=> The date is 2003-08-06

# the function strftime() (string-format time) produces nice formatting
# All codes are detailed at http://www.python.org/doc/current/lib/module-time.html
print t.strftime("four-digit year: %Y, two-digit year: %y, month: %m, day: %d")
#=> four-digit year: 2003, two-digit year: 03, month: 08, day: 06

Converting DMYHMS to Epoch Seconds

#-----------------------------
# Converting DMYHMS to Epoch Seconds
# To work with Epoch Seconds, you need to use the time module

# For the local timezone
t = datetime.datetime.now()
print "Epoch Seconds:", time.mktime(t.timetuple())
#=> Epoch Seconds: 1060199000.0

# For UTC
t = datetime.datetime.utcnow()
print "Epoch Seconds:", time.mktime(t.timetuple())
#=> Epoch Seconds: 1060195503.0

Converting Epoch Seconds to DMYHMS

#-----------------------------
# Converting Epoch Seconds to DMYHMS

now = datetime.datetime.fromtimestamp(EpochSeconds)
#or use datetime.datetime.utcfromtimestamp()
print now
#=> datetime.datetime(2003, 8, 6, 20, 43, 20)
print now.ctime()
#=> Wed Aug 6 20:43:20 2003

# or with the time module
oldtimetuple = time.localtime(EpochSeconds)
# oldtimetuple contains (year, month, day, hour, minute, second, weekday, yearday, daylightSavingAdjustment)
print oldtimetuple
#=> (2003, 8, 6, 20, 43, 20, 2, 218, 1)

Adding to or Subtracting from a Date

#-----------------------------
# Adding to or Subtracting from a Date
# Use the rather nice datetime.timedelta objects

now = datetime.date(2003, 8, 6)
difference1 = datetime.timedelta(days=1)
difference2 = datetime.timedelta(weeks=-2)

print "One day in the future is:", now + difference1
#=> One day in the future is: 2003-08-07

print "Two weeks in the past is:", now + difference2
#=> Two weeks in the past is: 2003-07-23

print datetime.date(2003, 8, 6) - datetime.date(2000, 8, 6)
#=> 1095 days, 0:00:00

#-----------------------------
birthtime = datetime.datetime(1973, 01, 18, 3, 45, 50) # 1973-01-18 03:45:50

interval = datetime.timedelta(seconds=5, minutes=17, hours=2, days=55)
then = birthtime + interval

print "Then is", then.ctime()
#=> Then is Wed Mar 14 06:02:55 1973

print "Then is", then.strftime("%A %B %d %I:%M:%S %p %Y")
#=> Then is Wednesday March 14 06:02:55 AM 1973

#-----------------------------
when = datetime.datetime(1973, 1, 18) + datetime.timedelta(days=55)
print "Nat was 55 days old on:", when.strftime("%m/%d/%Y").lstrip("0")
#=> Nat was 55 days old on: 3/14/1973

Difference of Two Dates

#-----------------------------
# Dates produce timedeltas when subtracted.

diff = date2 - date1
diff = datetime.date(year1, month1, day1) - datetime.date(year2, month2, day2)
#-----------------------------

bree = datetime.datetime(1981, 6, 16, 4, 35, 25)
nat = datetime.datetime(1973, 1, 18, 3, 45, 50)

difference = bree - nat
print "There were", difference, "minutes between Nat and Bree"
#=> There were 3071 days, 0:49:35 between Nat and Bree

weeks, days = divmod(difference.days, 7)

minutes, seconds = divmod(difference.seconds, 60)
hours, minutes = divmod(minutes, 60)

print "%d weeks, %d days, %d:%d:%d" % (weeks, days, hours, minutes, seconds)
#=> 438 weeks, 5 days, 0:49:35

#-----------------------------
print "There were", difference.days, "days between Bree and Nat."
#=> There were 3071 days between bree and nat

Day in a Week/Month/Year or Week Number

#-----------------------------
# Day in a Week/Month/Year or Week Number

when = datetime.date(1981, 6, 16)

print "16/6/1981 was:"
print when.strftime("Day %w of the week (a %A). Day %d of the month (%B).")
print when.strftime("Day %j of the year (%Y), in week %W of the year.")

#=> 16/6/1981 was:
#=> Day 2 of the week (a Tuesday). Day 16 of the month (June).
#=> Day 167 of the year (1981), in week 24 of the year.

Parsing Dates and Times from Strings

#-----------------------------
# Parsing Dates and Times from Strings

time.strptime("Tue Jun 16 20:18:03 1981")
# (1981, 6, 16, 20, 18, 3, 1, 167, -1)

time.strptime("16/6/1981", "%d/%m/%Y")
# (1981, 6, 16, 0, 0, 0, 1, 167, -1)
# strptime() can use any of the formatting codes from time.strftime()

# The easiest way to convert this to a datetime seems to be;
now = datetime.datetime(*time.strptime("16/6/1981", "%d/%m/%Y")[0:5])
# the '*' operator unpacks the tuple, producing the argument list.

Printing a Date

#-----------------------------
# Printing a Date
# Use datetime.strftime() - see helpfiles in distro or at python.org

print datetime.datetime.now().strftime("The date is %A (%a) %d/%m/%Y")
#=> The date is Friday (Fri) 08/08/2003

High-Resolution Timers

#-----------------------------
# High Resolution Timers

t1 = time.clock()
# Do Stuff Here
t2 = time.clock()
print t2 - t1

# 2.27236813618
# Accuracy will depend on platform and OS,
# but time.clock() uses the most accurate timer it can

time.clock(); time.clock()
# 174485.51365466841
# 174485.55702610247

#-----------------------------
# Also useful;
import timeit
code = '[x for x in range(10) if x % 2 == 0]'
eval(code)
# [0, 2, 4, 6, 8]

t = timeit.Timer(code)
print "10,000 repeats of that code takes:", t.timeit(10000), "seconds"
print "1,000,000 repeats of that code takes:", t.timeit(), "seconds"

# 10,000 repeats of that code takes: 0.128238644856 seconds
# 1,000,000 repeats of that code takes: 12.5396490336 seconds

#-----------------------------
import timeit
code = 'import random; l = random.sample(xrange(10000000), 1000); l.sort()'
t = timeit.Timer(code)

print "Create a list of a thousand random numbers. Sort the list. Repeated a thousand times."
print "Average Time:", t.timeit(1000) / 1000
# Time taken: 5.24391507859

Short Sleeps

#-----------------------------
# Short Sleeps

seconds = 3.1
time.sleep(seconds)
print "boo"

Program: hopdelta

#-----------------------------
# Program HopDelta
# Save a raw email to disk and run "python hopdelta.py FILE"
# and it will process the headers and show the time taken
# for each server hop (nb: if server times are wrong, negative dates
# might appear in the output).

import datetime, email, email.Utils
import os, sys, time

def extract_date(hop):
# According to RFC822, the date will be prefixed with
# a semi-colon, and is the last part of a received
# header.
date_string = hop[hop.find(';')+2:]
date_string = date_string.strip()
time_tuple = email.Utils.parsedate(date_string)

# convert time_tuple to datetime
EpochSeconds = time.mktime(time_tuple)
dt = datetime.datetime.fromtimestamp(EpochSeconds)
return dt

def process(filename):
# Main email file processing
# read the headers and process them
f = file(filename, 'rb')
msg = email.message_from_file(f)

hops = msg.get_all('received')

# in reverse order, get the server(s) and date/time involved
hops.reverse()
results = []
for hop in hops:
hop = hop.lower()

if hop.startswith('by'): # 'Received: by' line
sender = "start"
receiver = hop[3:hop.find(' ',3)]
date = extract_date(hop)

else: # 'Received: from' line
sender = hop[5:hop.find(' ',5)]
by = hop.find('by ')+3
receiver = hop[by:hop.find(' ', by)]
date = extract_date(hop)

results.append((sender, receiver, date))
output(results)

def output(results):
print "Sender, Recipient, Time, Delta"
print
previous_dt = delta = 0
for (sender, receiver, date) in results:
if previous_dt:
delta = date - previous_dt

print "%s, %s, %s, %s" % (sender,
receiver,
date.strftime("%Y/%d/%m %H:%M:%S"),
delta)
print
previous_dt = date

def main():
# Perform some basic argument checking
if len(sys.argv) != 2:
print "Usage: mailhop.py FILENAME"

else:
filename = sys.argv[1]
if os.path.isfile(filename):
process(filename)
else:
print filename, "doesn't seem to be a valid file."

if __name__ == '__main__':
main()

Tuesday, March 16, 2010

mootools inject

******************************************** mootool inject 1

====================== js

var Milestone = new Class({
initialize: function(el) {
this.element = $(el);
// console.log(this.element)
this.checkbox = this.element.getElement('.is-completed');
// console.log("ccc",this.checkbox);
if (this.checkbox != null) {
this.checkbox.addEvent('click',this.submit.bindWithEvent(this));
this.url = this.element.getElement('a.hidden-link').get('href');
this.element.getElement('.title').addEvent('mouseover',this.operationShow.bindWithEvent(this));
this.element.getElement('.title').addEvent('mouseout',this.operationHide.bindWithEvent(this));
this.request = new Request({ url: this.url});
this.request.addEvent('success', this.success.bind(this));
}
},


submit: function(ev) {
ev.stop();
this.element.getElement('.request-progress').setStyle('display','');
this.request.post({value:this.checkbox.checked});
},


success: function(response) {
if (this.checkbox.checked == true) {
this.checkbox.checked = false;
}else {
this.checkbox.checked = true;
}
this.element.getElement('.request-progress').setStyle('display','none');

var d = new Element('div', { 'html': response });
var l = d.getElement('.late-block');
var u = d.getElement('.upcoming-block');
var c = d.getElement('.completed-block');
var late = l.getElement('.inner-block');
var upcoming = u.getElement('.inner-block');
var completed = c.getElement('.inner-block');

completed.inject(document.getElement('.completed-block'));
document.getElement('.completed-block').getElement('.inner-block').dispose();
late.inject(document.getElement('.late-block'));
document.getElement('.late-block').getElement('.inner-block').dispose();
upcoming.inject(document.getElement('.upcoming-block'));
document.getElement('.upcoming-block').getElement('.inner-block').dispose();

$$('.milestone',d).each(function(el) {
var x = new Milestone(el);
});

},

operationShow: function(ev) {
ev.stop();
this.element.getElement('.operations').setStyles({display:'block'});
},

operationHide: function(ev) {
ev.stop();
var e = this.element.getElement('.operations');
e.setStyle.delay(2500, e, ['display','none']);
}

});


window.addEvent('domready', function() {
$$('.milestone').each(function(el) {
var x = new Milestone(el);
});
});


====================== Template

{% extends "siren/base_project.html" %}
{% load siren %}
{% load humanize %}

{% block title %}List Milestone{% endblock %}

{% block extrahead %}
<link rel="stylesheet" type="text/css" href="/media/css/milestone.css" />
<script type="text/javascript" src="/media/js/milestone.js"></script>
{% endblock %}

{% block content %}
<div class="title-block">
<h1>Milestones</h1><span class="date">(Today is {% now "jS F" %})</span>
<a href="{% url milestone_add project.id %}">New Milestone</a>
<br class="clear"/>
</div>

<div class="late-block">
<div class="inner-block">
{% if late_milestones %}
<h4>Late Milestones</h4>
{% for milestone in late_milestones %}
<span class="late-days">{{ milestone.due_date|num_days }} days late</span>
<span class="created-on">({{milestone.created_on|naturalday:"d M Y"|capfirst}})</span>
<span class="created-by">{{milestone.created_by}}</span>
{% include "siren/milestone/milestone_fragment.html" %}
{% endfor %}
{% endif %}
</div>
</div>


<div class="upcoming-block">
<div class="inner-block">
{% if milestones %}
<h4>Upcoming Milestones</h4>
{% for milestone in milestones %}
<span class="created-on">({{milestone.created_on|naturalday:"d M Y"|capfirst}})</span>
<span class="created-by">{{milestone.created_by}}</span>
{% include "siren/milestone/milestone_fragment.html" %}
{% endfor %}
{% endif %}
</div>
</div>


<div class="completed-block">
<div class="inner-block">
{% if completed_milestones %}
<h4>Completed Milestones</h4>
{% for milestone in completed_milestones %}
<span class="created-on">({{milestone.created_on|naturalday:"d M Y"|capfirst}})</span>
<span class="created-by">{{milestone.created_by}}</span>
{% include "siren/milestone/milestone_fragment.html" %}
{% endfor %}
{% endif %}
</div>
</div>


{% endblock %}

{% block rightsidebar %}<!--
<div class="current-time">{% now "M d, Y h:i A" %}</div>-->
{% endblock %}

======================

******************************************** mootool inject 2

var Milestone = new Class({
initialize: function(el) {
this.element = $(el);
// console.log(this.element)
this.checkbox = this.element.getElement('.is-completed');
// console.log("ccc",this.checkbox);
if (this.checkbox != null) {
this.checkbox.addEvent('click',this.submit.bindWithEvent(this));
this.url = this.element.getElement('a.hidden-link').get('href');
this.element.getElement('.title').addEvent('mouseover',this.operationShow.bindWithEvent(this));
this.element.getElement('.title').addEvent('mouseout',this.operationHide.bindWithEvent(this));
this.request = new Request({ url: this.url});
this.request.addEvent('success', this.success.bind(this));
}
},


submit: function(ev) {
ev.stop();
this.element.getElement('.request-progress').setStyle('display','');
this.request.post({value:this.checkbox.checked});
},


success: function(response) {
if (this.checkbox.checked == true) {
this.checkbox.checked = false;
}else {
this.checkbox.checked = true;
}
this.element.getElement('.request-progress').setStyle('display','none');

var d = new Element('div', { 'html': response });
var l = d.getElement('.late-block');
var u = d.getElement('.upcoming-block');
var c = d.getElement('.completed-block');

document.getElement('.late-block').dispose();
l.inject(document.getElement('.main-block'), 'bottom');
document.getElement('.upcoming-block').dispose();
u.inject(document.getElement('.main-block'), 'bottom');
document.getElement('.completed-block').dispose();
c.inject(document.getElement('.main-block'), 'bottom');

$$('.milestone').each(function(el) {
var x = new Milestone(el);
});

},

operationShow: function(ev) {
ev.stop();
this.element.getElement('.operations').setStyles({display:'block'});
},

operationHide: function(ev) {
ev.stop();
var e = this.element.getElement('.operations');
e.setStyle.delay(2500, e, ['display','none']);
}

});


window.addEvent('domready', function() {
$$('.milestone').each(function(el) {
var x = new Milestone(el);
});
});


======================


{% extends "siren/base_project.html" %}
{% load siren %}
{% load humanize %}

{% block title %}List Milestone{% endblock %}

{% block extrahead %}
<link rel="stylesheet" type="text/css" href="/media/css/milestone.css" />
<script type="text/javascript" src="/media/js/milestone.js"></script>
{% endblock %}

{% block content %}
<div class="title-block">
<h1>Milestones</h1><span class="date">(Today is {% now "jS F" %})</span>
<a href="{% url milestone_add project.id %}">New Milestone</a>
<br class="clear"/>
</div>

<div class="main-block">
<div class="late-block">
<div class="inner-block">
{% if late_milestones %}
<h4>Late Milestones</h4>
{% for milestone in late_milestones %}
<span class="late-days">{{ milestone.due_date|num_days }} days late</span>
<span class="created-on">({{milestone.created_on|naturalday:"d M Y"|capfirst}})</span>
<span class="created-by">{{milestone.created_by}}</span>
{% include "siren/milestone/milestone_fragment.html" %}
{% endfor %}
{% endif %}
</div>
</div>


<div class="upcoming-block">
<div class="inner-block">
{% if milestones %}
<h4>Upcoming Milestones</h4>
{% for milestone in milestones %}
<span class="created-on">({{milestone.created_on|naturalday:"d M Y"|capfirst}})</span>
<span class="created-by">{{milestone.created_by}}</span>
{% include "siren/milestone/milestone_fragment.html" %}
{% endfor %}
{% endif %}
</div>
</div>


<div class="completed-block">
<div class="inner-block">
{% if completed_milestones %}
<h4>Completed Milestones</h4>
{% for milestone in completed_milestones %}
<span class="created-on">({{milestone.created_on|naturalday:"d M Y"|capfirst}})</span>
<span class="created-by">{{milestone.created_by}}</span>
{% include "siren/milestone/milestone_fragment.html" %}
{% endfor %}
{% endif %}
</div>
</div>
<div>

{% endblock %}

{% block rightsidebar %}<!--
<div class="current-time">{% now "M d, Y h:i A" %}</div>-->
{% endblock %}


======================

Friday, March 12, 2010

Setting dynamic css class using filter in django


Setting dynamic css class using filter in django

=============================
How to set dynamic css class using filter in django

----------------------------- description

if you have a dict like { 'T': 'todo-type', 'ME': 'message-type' ...}
you can just use a filter like
timeline.type|timeline_type_class
which returns
timeline_type_map[timeline_type]
now
the next problem is
if you define this mapping near the filter
you know have two different places where the list of timeline types are kept
it will be easier to code if they are in a single place
so its better to place this in models.py
something like:
TYPE_MAP = [ ('M', ['Milestone', 'milestone-type']), ..... ]
then, you can generate the TYPE_CHOICES like this
[ (x[0], y[0]) for x,y in TYPE_MAP]
and you can generate the needed data for filter by doing
dict([ (x[0], y[1]) for x,y in TYPE_MAP])
we did all this code, simply for the reason that, we now have only a single place to edit, if we need to add more types
otherwise, we have to edit all over the place

------------------ in model

class Event(models.Model):

TYPE_MAP = [ ('TL', ['Todolist', 'todolist-type']),
('T', ['Todo', 'todo-type']),
('P', ['Project', 'project-type']),
('C', ['Category', 'category-type']),
('A', ['Activity', 'activity-type']),
('PM', ['Milestone', 'member-type']),
('MS', ['Mockupset', 'mockupset-type']),
('MU', ['Mockup', 'mockup-type']),
('M', ['Milestone', 'milestone-type']),
('MIC', ['Comment-Mi', 'milestone-comment-type']),
('ME', ['Message', 'message-type']),
('MEC', ['Comment-Me', 'message-comment-type']),
('TK', ['Ticket', 'ticket-type']),
('TKC', ['Comment-Tk', 'ticket-comment-type']),
]


TYPE_CHOICES = [(x, y[0]) for x,y in TYPE_MAP]


TYPE_ACTIONS = (
('A', 'Added'),
('U', 'Updated'),
('D', 'Deleted'),
('C', 'Completed'),
('R', 'Reassigned'),
('CL', 'Closed'),
)

type = models.CharField(max_length=3, choices=TYPE_CHOICES)
description = models.TextField()
created_on = models.DateTimeField()
done_by = models.ForeignKey(User)
project = models.ForeignKey(Project)
action = models.CharField(max_length=2, choices=TYPE_ACTIONS)
url = models.URLField()
objects = EventManager()

------------------ in tag file (/templatetags/filename.py)

@register.filter
def timeline_type_class(type):
#print dict(Event.TYPE_CHOICES)
type_choices = [(x, y[1]) for x,y in Event.TYPE_MAP]
for x in type_choices:
if type == x[0]:
return x[1]


------------------ in template

<ul>
{% for timeline in timelines %}
<li>
<span class="{{ timeline.type|timeline_type_class }} type">
{{ timeline.get_type_display }}
</span>
<span class="action">{{ timeline.get_action_display }} <a href="{{timeline.url}}">{{ timeline.description }}</a></span>
<span class="name">{{ timeline.get_action_display }} by {{ timeline.done_by }}</span>
</li>
{% endfor %}
</ul>

------------------ in css file

span.todo-type {
background-color: #C87800;
}

span.milestone-type {
background-color: #5F6E43;
}

span.message-type {
background-color: #334E7D;
}

span.comments-type {
background-color: #6493AC;
}

span.todolist-type {
background-color: #5493AC;
}

span.member-type {
background-color: #3493AC;
}

span.activity-type {
background-color: #8493AC;
}

span.category-type {
background-color: #6000AC;
}

span.mockup-type {
background-color: maroon;
}

span.mockupset-type {
background-color: orange;
}

span.project-type {
background-color: #AC7981;
}

span.ticket-type {
background-color: #107A81;
}

span.message-comment-type {
background-color: #BA7A81;
}

span.milestone-comment-type {
background-color: #CF7A11;
}

span.ticket-comment-type {
background-color: #CF0AA1;
}

span.type {
display: block;
float: left;
width: 70px;
text-align: right;
color: #FFFFFF;
padding: 2px 5px 2px 2px;
margin-bottom: 3px;
}


------------------ Note

1)

TYPE_CHOICES = [(x, y[0]) for x,y in TYPE_MAP] <------------

* This code create a list of touples.
* Type print TYPE_CHOICES to list of touples like below.

output look like:

[
('TL', 'Todolist'),
('T', 'Todo'),
('P', 'Project'),
('C', 'Category'),
('A', 'Activity'),
('PM', 'Milestone'),
('MS', 'Mockupset'),
('MU', 'Mockup'),
('M', 'Milestone'),
('MIC', 'Comment-Mi'),
('ME', 'Message'),
('MEC', 'Comment-Me'),
('TK', 'Ticket'),
('TKC', 'Comment-Tk')
]


2)

* Use dict() method to convert list of tuples to dictionary.

dict([(x, y[0]) for x,y in TYPE_MAP]) <------------
or
TYPE_CHOICES = [(x, y[0]) for x,y in TYPE_MAP]
dict(TYPE_CHOICES)

output look like:

{
'A': 'Activity',
'ME': 'Message',
'C': 'Category',
'TKC': 'Comment-Tk',
'MEC': 'Comment-Me',
'MIC': 'Comment-Mi',
'M': 'Milestone',
'MU': 'Mockup',
'P': 'Project',
'TL': 'Todolist',
'T': 'Todo',
'MS': 'Mockupset',
'TK': 'Ticket',
'PM': 'Milestone'
}


3)

TYPE_CHOICES = [(x, y[1]) for x,y in TYPE_MAP] <------------
print TYPE_CHOICES

output look like:

[
('TL', 'todolist-type'),
('T', 'todo-type'),
('P', 'project-type'),
('C', 'category-type'),
('A', 'activity-type'),
('PM', 'member-type'),
('MS', 'member-type'),
('MU', 'member-type'),
('M', 'milestone-type'),
('MIC', 'milestone-comment-type'),
('ME', 'message-type'),
('MEC', 'message-comment-type'),
('TK', 'member-type'),
('TKC', 'member-type')
]


------------------


**************************************************************

Wednesday, March 10, 2010

how to django template simple tag

how to django template simple tag

----------------- in template

{% can_edit_comment comment.created_on %} <--- Important: it directly print return value.

----------------- in /templatetags/siren.py

from django import template
register = template.Library()

@register.simple_tag
def can_edit_comment(created_on):
print "created_on",created_on
print "edit time", created_on + datetime.timedelta(minutes=35)

edit_time = created_on + datetime.timedelta(minutes=35)

print "today", datetime.datetime.today()

if edit_time > datetime.datetime.today():
print "can edit"
return True
else:
print "not edit"
return False


----------------------

how to django custom template tab

how to django custom template tab

----------------in template

{% can_edit_comment value comment.created_on %}

{% if value %}
hi
{% endif %}

----------------in /templatetags/siren.py

class CanEditCommentNode(template.Node):
def __init__(self ,tag_name, variable, created_on):
self.variable = variable
self.tag_name = tag_name
self.created_on = created_on

def render(self, context):
created = template.resolve_variable(self.created_on, context)
edit_time = created + datetime.timedelta(minutes=55)
print "today", datetime.datetime.today()

if edit_time > datetime.datetime.today():
print "can edit"
context[self.variable] = True
else:
print "not edit"
context[self.variable] = False
return ''



@register.tag
def can_edit_comment(parser, token):
try:
tag_name, variable, created_on = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError
return CanEditCommentNode(tag_name, variable, created_on)

------------------------

how to register irc nickname

how to register irc nickname

1) /msg NickServ help

2) /msg NickServ help register

3) /msg NickServ register 123456 xxxx@gmail.com


-------------------------------------1

/msg NickServ help <--------

[09:23] <-> NickServ> help
[09:23] [Notice] -NickServ- ***** NickServ Help *****
[09:23] [Notice] -NickServ- NickServ allows users to 'register' a nickname, and stop
[09:23] [Notice] -NickServ- others from using that nick. NickServ allows the owner of a
[09:23] [Notice] -NickServ- nickname to disconnect a user from the network that is using
[09:23] [Notice] -NickServ- their nickname.
[09:23] [Notice] -NickServ-
[09:23] [Notice] -NickServ- For more information on a command, type:
[09:23] [Notice] -NickServ- /msg NickServ help
[09:23] [Notice] -NickServ- For a verbose listing of all commands, type:
[09:23] [Notice] -NickServ- /msg NickServ help commands
[09:23] [Notice] -NickServ-
[09:23] [Notice] -NickServ- The following commands are available:
[09:23] [Notice] -NickServ- GHOST Reclaims use of a nickname.
[09:23] [Notice] -NickServ- GROUP Adds a nickname to your account.
[09:23] [Notice] -NickServ- UNGROUP Removes a nickname from your account.
[09:23] [Notice] -NickServ- IDENTIFY Identifies to services for a nickname.
[09:23] [Notice] -NickServ- INFO Displays information on registrations.
[09:23] [Notice] -NickServ- LISTCHANS Lists channels that you have access to.
[09:23] [Notice] -NickServ- REGISTER Registers a nickname.
[09:23] [Notice] -NickServ- SET Sets various control flags.
[09:23] [Notice] -NickServ- RELEASE Releases a services enforcer.
[09:23] [Notice] -NickServ-
[09:23] [Notice] -NickServ- Other commands: ACCESS, DROP, HELP, LISTOWNMAIL, LOGOUT,
[09:23] [Notice] -NickServ- SETPASS, ACC, STATUS, TAXONOMY, VERIFY,
[09:23] [Notice] -NickServ- VACATION
[09:23] [Notice] -NickServ- ***** End of Help *****


-------------------------------------2

/msg NickServ help register <---------

[09:24] <-> NickServ> help register
[09:24] [Notice] -NickServ- ***** NickServ Help *****
[09:24] [Notice] -NickServ- Help for REGISTER:
[09:24] [Notice] -NickServ-
[09:24] [Notice] -NickServ- This will register your current nickname with NickServ.
[09:24] [Notice] -NickServ- This will allow you to assert some form of identity on
[09:24] [Notice] -NickServ- the network and to be added to access lists. Furthermore,
[09:24] [Notice] -NickServ- NickServ will warn users using your nick without
[09:24] [Notice] -NickServ- identifying and allow you to kill ghosts.
[09:24] [Notice] -NickServ- The password is a case-sensitive password that you make
[09:24] [Notice] -NickServ- up. Please write down or memorize your password! You
[09:24] [Notice] -NickServ- will need it later to change settings.
[09:24] [Notice] -NickServ-
[09:24] [Notice] -NickServ- You have to confirm the email address. To do this,
[09:24] [Notice] -NickServ- follow the instructions in the message sent to the email
[09:24] [Notice] -NickServ- address.
[09:24] [Notice] -NickServ-
[09:24] [Notice] -NickServ- Syntax: REGISTER
[09:24] [Notice] -NickServ-
[09:24] [Notice] -NickServ- Examples:
[09:24] [Notice] -NickServ- /msg NickServ REGISTER bar foo@bar.com
[09:24] [Notice] -NickServ- ***** End of Help *****

-------------------------------------------3

/msg NickServ register 123456 xxxx@gmail.com <-------


-------------------------------------------

Thursday, March 4, 2010

Django Mootool Ajax 1

***********************************************
Django Mootool Ajax 1

========================================== js

var Milestone = new Class({
initialize: function(el) { <---------- constructor
this.element = $(el); <----------
// console.log(this.element)
this.checkbox = this.element.getElement('.is-completed');
this.checkbox.addEvent('click',this.submit.bindWithEvent(this));
this.url = this.element.getElement('a').get('href');
// console.log('href', this.url)
this.request = new Request({ url: this.url}); <----------
this.request.addEvent('success', this.success.bind(this)); <----------
},

submit: function(ev) {
ev.stop(); <----------
this.element.getElement('.request-progress').setStyle('display',''); <----------
this.request.post({value:this.checkbox.checked}); <----------
console.log('clicked')
},

success: function(response) {
// console.log('success');
if (this.checkbox.checked == true) {
this.checkbox.checked = false;
}else {
this.checkbox.checked = true;
}
this.element.getElement('.request-progress').setStyle('display','none'); <----------

var d = new Element('div', { 'html': response });
var l = d.getElement('.late-block');
var u = d.getElement('.upcoming-block');
var c = d.getElement('.completed-block');
var late = l.getElement('.inner-block');
var upcoming = u.getElement('.inner-block');
var completed = c.getElement('.inner-block');

completed.inject(document.getElement('.completed-block')); <---------- inject
document.getElement('.completed-block').getElement('.inner-block').dispose(); <---------- dispose
late.inject(document.getElement('.late-block'));
document.getElement('.late-block').getElement('.inner-block').dispose();
upcoming.inject(document.getElement('.upcoming-block'));
document.getElement('.upcoming-block').getElement('.inner-block').dispose();

$$('.milestone',d).each(function(el) {
var x = new Milestone(el);
});
}

});

window.addEvent('domready', function() { <----------
$$('.milestone').each(function(el) {
var x = new Milestone(el);
});
// console.log('ok')
});

======================================== milestone_fragment.html

<div class="milestone">
<input type="checkbox" class="is-completed" name="is_completed" {% if milestone.is_completed %} checked=true {%endif%}>
<a href="{% url set_completed project.id milestone.id %}" style="display:none"></a>
<span class="title">{{ milestone.title|capfirst }}</span>
<img src="/media/graphics/ajax_loader.gif" id="request-progress" class="request-progress" style="display:none;" />
<ul class="todolist">
{% for todolist in milestone.todolists %}
<li>{{ todolist.name }}</li>
{% endfor %}
</ul>
</div>

======================================== milestone_list.htlm

{% extends "siren/base_project.html" %}
{% load siren %}
{% load humanize %}

{% block title %}List Milestone{% endblock %}

{% block extrahead %}
<link rel="stylesheet" type="text/css" href="/media/css/milestone.css" />
<script type="text/javascript" src="/media/js/milestone.js"></script>
{% endblock %}

{% block content %}
<div class="title-block">
<h1>Milestones</h1><span class="date">(Today is {% now "jS F" %})</span>
<a href="{% url milestone_add project.id %}">New Milestone</a>
<br class="clear"/>
</div>

<div class="late-block">
<h4>Late Milestones</h4>
<div class="inner-block">
{% for milestone in late_milestones %}
{% include "siren/milestone/milestone_fragment.html" %}
{% endfor %}
</div>
</div>


<div class="upcoming-block">
<h4>Upcoming Milestones</h4>
<div class="inner-block">
{% for milestone in milestones %}
{% include "siren/milestone/milestone_fragment.html" %}
{% endfor %}
</div>
</div>


<div class="completed-block">
<h4>Completed Milestones</h4>
<div class="inner-block">
{% for milestone in completed_milestones %}
{% include "siren/milestone/milestone_fragment.html" %}
{% endfor %}
</div>
</div>

{% endblock %}

{% block rightsidebar %}
{% endblock %}

================================= views.py (for handle Ajax request)

@login_required
def set_completed(request, project_id, milestone_id):
project = get_object_or_404(Project, pk=project_id)
milestone = get_object_or_404(Milestone, pk=milestone_id)
if request.is_ajax(): <---------------------
print "-->", request.POST
if request.POST['value'] == 'true':
status = True
else:
status = False
milestone.is_completed = status
milestone.save()
milestones = project.milestone_set.filter(is_completed=False, due_date__gt=datetime.datetime.today())
late_milestones = Milestone.objects.filter(
is_completed=False,
due_date__lt=datetime.datetime.today(),
project__projectmember__user=request.user,
project=project
)
completed_milestones = Milestone.objects.filter(
is_completed=True,
project__projectmember__user=request.user,
project=project
)
return render_to_response('siren/milestone/milestone_list.html', {
'milestones':milestones,
'late_milestones':late_milestones,
'completed_milestones':completed_milestones,
'project':project
}, context_instance=RequestContext(request))


=============================== views.py (for first list display)

@login_required
def milestone_list(request, project_id):
project = get_object_or_404(Project, pk=project_id)
if request.method == 'GET':
milestones = project.milestone_set.filter(is_completed=False, due_date__gt=datetime.datetime.today())
late_milestones = Milestone.objects.filter(
is_completed=False,
due_date__lt=datetime.datetime.today(),
project__projectmember__user=request.user,
project=project
)
completed_milestones = Milestone.objects.filter(
is_completed=True,
project__projectmember__user=request.user,
project=project
)
return render_to_response('siren/milestone/milestone_list.html', {
'milestones':milestones,
'late_milestones':late_milestones,
'completed_milestones':completed_milestones,
'project':project
}, context_instance=RequestContext(request))

===============================

**********************************************

Tuesday, March 2, 2010

Django Customizing the comments framework

Django Customizing the comments framework

****************************************

{% render_comment_form for message %}

****************************************

{% get_comment_form for message as form %}

<form action="{% comment_form_target %}" method="POST">
{{ form }}
<tr>
<td></td>
<td><input type="submit" name="preview" class="submit-post" value="Preview"></td>
</tr>
</form>


****************************************

<form action=" {% comment_form_target %} " method="POST">

{% for field in form %}

{% if field.is_hidden %}

{{ field }}

{% else %}

<p

{% if field.errors %} class="error"{% endif %}

{% ifequal field.name "honeypot" %}
style="display:none;"{% endifequal %}>

{% if field.errors %}{{ field.errors }}{% endif %}

{{ field.label_tag }} {{ field }}

</p>

****************************************

{% get_comment_form for message as form %}

<form action=" {% comment_form_target %} " method="POST">

{% for field in form %}

{% if field.is_hidden %}
{{ field }}
{% endif %}

{% ifequal field.name "comment" %} {{ field }}{% endifequal %}

{% endfor %}
<p class="submit">
<input type="submit" value="Post" class="submit-post" name="post">
<input type="submit" value="Preview" class="submit-preview" name="preview">
</p>
</form>

****************************************

You can remove fields from templates (from html). They indeed should
be removed if you don't want them :)
Then we face a problem: some of CommentForm fields are marked as
required. The solution is to subclass CommentForm and set this flag to
False:

class NoEmailForm(CommentForm):
def __init__(self, target_object, data=None, initial=None):
super(NoEmailForm, self).__init__(target_object, data,
initial)
self.fields['email'].required = False

****************************************

BaseCommentAbstractModel

****************************************working

{% get_comment_form for message as form %}

<form action=" {% comment_form_target %} " method="POST">

{% for field in form %}

{% if field.is_hidden %}
{{ field }}
{% endif %}

{% ifequal field.name "comment" %} {{ field }}{% endifequal %}

{% endfor %}
<p class="submit">
<input type="submit" value="Post" class="submit-post" name="post">
<!-- <input type="submit" value="Preview" class="submit-preview" name="preview"> -->
</p>
</form>


**************************************** works
<h4>Comments </h4>

{% get_comment_list for message as comment_list %}
{% for comment in comment_list %}
{{ comment.comment }} <br>
{% endfor %}


{% get_comment_form for message as form %}

<form action=" {% comment_form_target %} " method="POST">
<input type="hidden" name="next" value="{% url message_detail project.id message.id %}" />
{% for field in form %}
{% if field.is_hidden %}
{{ field }}
{% endif %}
{% ifequal field.name "comment" %} {{ field }}{% endifequal %}
{% endfor %}
<p class="submit">
<input type="submit" value="Post" class="submit-post" name="post">
<!-- <input type="submit" value="Preview" class="submit-preview" name="preview"> -->
</p>
</form>


****************************************


****************************************