<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Dr. Pink Pony</title>
	<atom:link href="http://drpinkpony.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://drpinkpony.wordpress.com</link>
	<description>Django is my passion. All in magical pink.</description>
	<lastBuildDate>Thu, 29 Jul 2010 05:50:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='drpinkpony.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Dr. Pink Pony</title>
		<link>http://drpinkpony.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://drpinkpony.wordpress.com/osd.xml" title="Dr. Pink Pony" />
	<atom:link rel='hub' href='http://drpinkpony.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Why my Django apps complains import errors in production but not with devserver?</title>
		<link>http://drpinkpony.wordpress.com/2010/07/28/django-import-errors/</link>
		<comments>http://drpinkpony.wordpress.com/2010/07/28/django-import-errors/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 16:32:58 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[setup]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=73</guid>
		<description><![CDATA[Cause Usually this happens when you&#8217;re using so called in-project apps (apps reside inside project directory itself). It&#8217;s just because you have incorrect PYTHONPATH setting. Whenever you run Django with ./manage.py runserver there happens two things. First Python will use current working directory as base search path. So first path to search is always &#8216;.&#8217; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=73&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h1>Cause</h1>
<p>Usually this happens when you&#8217;re using so called in-project apps (apps reside inside project directory itself). It&#8217;s just because you have incorrect PYTHONPATH setting.</p>
<p>Whenever you run Django with ./manage.py runserver there happens two things. First Python will use current working directory as base search path. So first path to search is always <em>&#8216;.&#8217;</em></p>
<h1>The simple fix</h1>
<p>To make it work you need to add your root to your project as well as project directory to PYTHONPATH, usually this is done in wsgi startup script.</p>
<pre class="brush: python;">
import sys

# Required to make project.settings to work
sys.path.append('/path/to/root/')

# required to make myapp.models and like imports to work
sys.path.append('/path/to/root/project/')
</pre>
</pre>
<p>Of course you can omit root and use only "settings" as a Django settings, but it has it's own caveats.</p>
<p>Personally I use out-of-project apps to avoid this particular problem.  Of course it requires that in even in development phase I need to setup PYTHONPATH as well to make everything work, but it will be consistent - I need to set it up always, not just in deployment phase.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/73/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/73/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/73/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=73&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2010/07/28/django-import-errors/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
		<item>
		<title>Serving CSS and images with Django</title>
		<link>http://drpinkpony.wordpress.com/2010/02/22/serving-css-and-images-with-django/</link>
		<comments>http://drpinkpony.wordpress.com/2010/02/22/serving-css-and-images-with-django/#comments</comments>
		<pubDate>Mon, 22 Feb 2010 20:21:21 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[image]]></category>
		<category><![CDATA[serving]]></category>
		<category><![CDATA[static]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=64</guid>
		<description><![CDATA[Even Django has excellent documentation and it covers serving static files. It&#8217;s not in-depth and let&#8217;s some details unexplained. Note that this article only applies to DEBUG mode, not production mode. Let&#8217;s start doing same thing as in tutorial and add serving static files when in debug mode. Add following lines in your top-level urls.py [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=64&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Even Django has excellent documentation and it covers <a href="http://docs.djangoproject.com/en/dev/howto/static-files/">serving static files</a>. It&#8217;s not in-depth and let&#8217;s some details unexplained. </p>
<p>Note that this article only applies to DEBUG mode, not production mode.</p>
<p>Let&#8217;s start doing same thing as in tutorial and add serving static files when in debug mode. Add following lines in your top-level urls.py file:</p>
<pre class="brush: python; gutter: false;">
from django.conf import settings

# ... your existing urls here

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^site_media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
    )
</pre>
<p>Most important thing here is to note url used. It&#8217;s <strong>/site_media/</strong>. You can change whatever you want, but note that by default admin uses <em>ADMIN_MEDIA_PREFIX = &#8216;/media/</em>&#8216;. If you accidentally override admin media url you get unwanted results in admin.</p>
<p>Next you have to change your <em>settings.py</em> file to have these new settings.</p>
<pre class="brush: python; gutter: false;">
MEDIA_URL = '/site_media/'
MEDIA_ROOT = '/absolute/path/to/media/root/'
</pre>
<p>MEDIA_URL is a url where your static files like CSS and images are going to be. MEDIA_ROOT is a path where your media files are located and where actually MEDIA_URL points to.</p>
<p>One useful trick to provide <em>MEDIA_ROOT</em> is to use &#8220;relative&#8221; path to your project (settings.py).</p>
<pre class="brush: python; gutter: false;">
import os
MEDIA_ROOT = os.path.abspath(os.path.dirname(__file__) + '/site_media/')
</pre>
<p>Last thing is to make sure your templates are correctly done:</p>
<p>Use always context variable (and context processors) like:</p>
<pre class="brush: xml; gutter: false;">
css&quot; href=&quot;{{ MEDIA_URL }}css/styles.css&quot; /&gt;

&lt;script type=&quot;text/&lt;span class=&quot;&gt;&lt;!--mce:0--&gt;&lt;/script&gt;

&lt;img src=&quot;{{ MEDIA_URL }}images/cat.png&quot; /&gt;
</pre>
<p>In your view code you have to use following:</p>
<pre class="brush: plain; gutter: false;">
return render_to_response('mytemplate.html', {},
  context_instance=RequestContext(request))
</pre>
<p>How this all ties together?</p>
<p>MEDIA_URL points to /site_media/ which then is appended in templates to your urls making them like /site_media/images/cat.png. Regular expression extracts last parts of URL (images/cat.png) which is then in turn appended to MEDIA_ROOT path by Django built-in view.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/64/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/64/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/64/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=64&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2010/02/22/serving-css-and-images-with-django/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
		<item>
		<title>How to see what SQL Django executes</title>
		<link>http://drpinkpony.wordpress.com/2010/02/08/how-to-see-what-sql-django-executes/</link>
		<comments>http://drpinkpony.wordpress.com/2010/02/08/how-to-see-what-sql-django-executes/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 19:00:25 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[db]]></category>
		<category><![CDATA[orm]]></category>
		<category><![CDATA[sql]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=59</guid>
		<description><![CDATA[Getting out what RAW SQL Django executes is simple. Just make sure that you have defined DEBUG=True in your settings file before trying all this out. This works with 1.1: qs = MyModel.objects.filter(pk=1) len(qs) # Evaluate queryset from django.db import connection; print connection.queries[-1] for Django 1.2 you do following (replace &#8216;default&#8217; with name of db [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=59&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Getting out what RAW SQL Django executes is simple. Just make sure that you have defined DEBUG=True in your settings file before trying all this out.</p>
<p>This works with 1.1:</p>
<pre class="brush: python; gutter: false;">
qs = MyModel.objects.filter(pk=1)
len(qs) # Evaluate queryset

from django.db import connection; print connection.queries[-1]
</pre>
<p>for Django 1.2 you do following (replace &#8216;default&#8217; with name of db if you want to check some explicit db):</p>
<pre class="brush: python; gutter: false;">
qs = MyModel.objects.filter(pk=1)
len(qs) # Evaluate queryset

from django.db import connections; print connections['default'].queries[-1]
</pre>
<p>By removing slicing, you can print all queries executed, as explained in Django documentation:</p>
<pre class="brush: python; gutter: false;">
from django.db import connection; print connection.queries # print all queries executed
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/59/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/59/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/59/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=59&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2010/02/08/how-to-see-what-sql-django-executes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
		<item>
		<title>Programming food</title>
		<link>http://drpinkpony.wordpress.com/2010/02/05/programming-food/</link>
		<comments>http://drpinkpony.wordpress.com/2010/02/05/programming-food/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 19:31:56 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=54</guid>
		<description><![CDATA[Every programmer needs to eat. Good programmer needs to eat a lot or an another alternative eat healthy, energy rich food. Today I&#8217;ll represent one of my favorite dishes cardiovascular omelet a.k.a. Heartbreak Kid. Originally this recipe is presented at www.kaenkky.com. First we need functional specs &#8211; dish must contain lot of fat, salt, chili [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=54&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Every programmer needs to eat. Good programmer needs to eat a lot or an another alternative eat healthy, energy rich food.</p>
<p>Today I&#8217;ll represent one of my favorite dishes cardiovascular omelet a.k.a. Heartbreak Kid. Originally this recipe is presented at <a href="http://www.kaenkky.com/?p=artl&amp;id=53">www.kaenkky.com</a>.</p>
<p>First we need functional specs &#8211; dish must contain lot of fat, salt, chili and taste good. Ok, that&#8217;s all for specs.</p>
<p>Technical specs:</p>
<ul>
<li>At least 5 eggs</li>
<li>Packet of bacon (around 150g)</li>
<li>Micropizza (salami, ham, meat. pick your favorite)</li>
<li>Black pepper</li>
<li>Salt</li>
<li>Tabasco</li>
<li>Oil</li>
<li>Smetana or in case of emergency crème fraîche</li>
<li>Hot chili if you like</li>
</ul>
<p>Implementation details:</p>
<p>Now it helps if you have two pans, heat them both and apply a bit of oil.</p>
<p>First we start preparing omelet. Take a bowl and beat eggs. Beat them good. It helps relieving stress that programming causes.</p>
<p>Start frying bacon on a one pan and put half of eggs on a second pan. When bacon is ready and first omelet is ready put bacon on top of first omelet. Add rest of eggs on free pan.</p>
<p>Top bacon with chili, Smetana, black pepper etc. Whatever you happen to like.</p>
<p>Heat micropizza in a micro.  put it upside down on top of first omelet and heat so pizza melts together with omelet.</p>
<p>When second omelet is almost ready, flip it over on top of first omelet.</p>
<p>Carefully move to plate and enjoy.</p>
<p>And to scare you all some approximate nutrition facts:</p>
<table>
<tbody>
<tr>
<th>Energy</th>
<td>7860 kJ</td>
</tr>
<tr>
<th>Protein</th>
<td>80 g</td>
</tr>
<tr>
<th>Carbohydrates</th>
<td>71 g</td>
</tr>
<tr>
<th>Fat</th>
<td>141 g</td>
</tr>
<tr>
<th>Cholesterol</th>
<td>1400 mg</td>
</tr>
<tr>
<th>Salt</th>
<td>5800 mg</td>
</tr>
</tbody>
</table>
<p>I&#8217;ll add pics later.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/54/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/54/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/54/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=54&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2010/02/05/programming-food/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
		<item>
		<title>Django AJAX authentication</title>
		<link>http://drpinkpony.wordpress.com/2010/02/02/django-ajax-authentication/</link>
		<comments>http://drpinkpony.wordpress.com/2010/02/02/django-ajax-authentication/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 21:04:26 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=51</guid>
		<description><![CDATA[Ajax is very fundamental tool for any RIA. Django makes it rather easy to interact with Ajax, specially if you&#8217;re using some of the common JavaScript frameworks like jQuery, Dojotoolkit or Ext-JS. To make things easy Let&#8217;s start by copying and modifying existing decorators from Django sources (note that these don&#8217;t work with Django 1.2): [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=51&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Ajax is very fundamental tool for any RIA. Django makes it rather easy to interact with Ajax, specially if you&#8217;re using some of the common JavaScript frameworks like jQuery, Dojotoolkit or Ext-JS.</p>
<p>To make things easy Let&#8217;s start by copying and modifying existing decorators from Django sources (note that these don&#8217;t work with Django 1.2):</p>
<pre class="brush: python;">
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.http import urlquote
from django.utils.functional import wraps
from django.utils.decorators import auto_adapt_to_methods
from django.contrib.auth import REDIRECT_FIELD_NAME

def user_passes_test_with_ajax(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    &quot;&quot;&quot;
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.

    Returns special response to ajax calls instead of blind redirecting.
    &quot;&quot;&quot;
    if not login_url:
        from django.conf import settings
        login_url = settings.LOGIN_URL

    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                return view_func(request, *args, **kwargs)
            path = urlquote(request.get_full_path())
            tup = login_url, redirect_field_name, path
            # Hook in ajax
            if not request.is_ajax():
                return HttpResponseRedirect('%s?%s=%s' % tup)
            else:
                # In case of ajax we send 401 - unauthorized HTTP response
                return HttpResponse('%s?%s=%s' % tup, status=401)

        return wraps(view_func)(_wrapped_view)
    return auto_adapt_to_methods(decorator)

def login_required_with_ajax(function=None, redirect_field_name=REDIRECT_FIELD_NAME):
    &quot;&quot;&quot;
    Decorator for views that checks that the user is logged in, redirecting
    to the log-in page if necessary.

    Takes account ajax handling with redirections
    &quot;&quot;&quot;
    actual_decorator = user_passes_test_with_ajax(
        lambda u: u.is_authenticated(),
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator
</pre>
<p>Then in a view code you just need to use our magical decorator:</p>
<pre class="brush: python;">
from decorators import login_required_with_ajax
from django.http import HttpResponse

@login_required_with_ajax
def test(request):
    return HttpResponse(&quot;Success!&quot;)
</pre>
<p>And for the last thing we need hookup in JavaScript. I made example with jQuery:</p>
<pre class="brush: xml;">
&lt;DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;
&lt;html&gt;
	&lt;head&gt;
		&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot;&gt;
		&lt;title&gt;AJAX authentication test&lt;/title&gt;
		&lt;script type=&quot;text/&lt;span class=&quot;&gt;&lt;!--mce:0--&gt;&lt;/script&gt;
		&lt;script type=&quot;text/javascript&quot;&gt;
			function test_ajax() {
				$.ajax({
					url : '/testview/',
					success : function (data, textStatus, request) {
						$('#_result').html(data);
					},
					error: function(request, textStatus, errorThrown){
						if (request.status == 401) {
							// Redirect to login
							window.location = request.responseText;
						}
					}
				});
			}
		&lt;/script&gt;
	&lt;/head&gt;
	&lt;body&gt;
		&lt;button type=&quot;button&quot; onclick=&quot;test_ajax()&quot;&gt;Test Ajax&lt;/button&gt;
		&lt;div&gt;Result was:&lt;span id=&quot;_result&quot;&gt;[Not tested yet]&lt;/span&gt;&lt;/div&gt;
	&lt;/body&gt;
&lt;/html&gt;
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/51/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/51/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/51/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/51/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/51/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/51/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/51/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/51/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/51/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/51/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/51/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/51/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/51/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/51/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=51&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2010/02/02/django-ajax-authentication/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
		<item>
		<title>Django cascade delete headache</title>
		<link>http://drpinkpony.wordpress.com/2010/01/28/django-cascade-delete-headache/</link>
		<comments>http://drpinkpony.wordpress.com/2010/01/28/django-cascade-delete-headache/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 19:10:58 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[models]]></category>
		<category><![CDATA[orm]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=45</guid>
		<description><![CDATA[Django uses by default ON DELETE CASCADE, which in most cases is alright. But sometimes it&#8217;s not what is wanted. There is ticket and patch in Django Trac, but meanwhile I created my own mixin that can be used in deletes: from django.db.models import OneToOneField, ObjectDoesNotExist from django.utils.encoding import StrAndUnicode from django.utils.translation import ugettext as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=45&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Django uses by default ON DELETE CASCADE, which in most cases is alright. But sometimes it&#8217;s not what is wanted.</p>
<p>There is ticket and patch in Django Trac, but meanwhile I created my own mixin that can be used in deletes:</p>
<pre class="brush: python;">
from django.db.models import OneToOneField, ObjectDoesNotExist
from django.utils.encoding import StrAndUnicode
from django.utils.translation import ugettext as _

class ForeignKeysExist(StrAndUnicode, Exception):
    def __init__(self, parent, child, field):
        '''
            Arguments:
            parent - parent instance (that contains child records)
            child  - object that have foreign key pointing to the parent instance
            field  - child instance foreign key field name
        '''
        self.parent = parent #parent instance
        self.child = child #child that has reference to this parent
        self.field = field #field in the child class that points to the parent
        self.msg =  _('Child record %s.%s exists for %s') % (_(child), _(field), _(parent))

        super(ForeignKeysExist, self).__init__(self.msg)

    def __unicode__(self):
        return self.msg

class NoDeleteCascadeMixin(object):
    &quot;&quot;&quot;
    Mixin to prevent deletion of model
    if there exists any children
    &quot;&quot;&quot;

    def delete(self):
        # Copied sanity test from django.db.models.ModelBase.delete
        assert self._get_pk_val() is not None, &quot;%s object can't be deleted because its %s attribute is set to None.&quot; % (self._meta.object_name, self._meta.pk.attname)

        opts = self._meta

        for related in opts.get_all_related_objects():
            rel_accessor = related.get_accessor_name()
            if isinstance(related, OneToOneField):
                try:
                    o = getattr(self, rel_accessor)
                except ObjectDoesNotExist:
                    pass # No item in one to one
                else:
                    raise ForeignKeysExist(related.parent_model._meta.object_name, opts.object_name, related.field.name)
            else:
                rel_manager = getattr(self, rel_accessor)
                if rel_manager.count():
                    raise ForeignKeysExist(related.parent_model._meta.object_name, related.model._meta.object_name, related.field.name)

        super(NoDeleteCascadeMixin, self).delete()
</pre>
<p>And usage is simple, just put NoDeleteCascadeMixin to your model as a first one.</p>
<pre class="brush: python;">
class MyModel(NoDeleteCascadeMixin, models.Model):
    # Fields here
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/45/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/45/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=45&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2010/01/28/django-cascade-delete-headache/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
		<item>
		<title>Django in Windows</title>
		<link>http://drpinkpony.wordpress.com/2010/01/17/django-in-windows/</link>
		<comments>http://drpinkpony.wordpress.com/2010/01/17/django-in-windows/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 19:04:05 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[install]]></category>
		<category><![CDATA[setup]]></category>
		<category><![CDATA[windows]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=41</guid>
		<description><![CDATA[Getting Django up and running on Windows is somewhat tricky. I used these instructions at our development department and publish these in hope that someone else can benefit of them too. First thing is to download and install Python. I suggest using latest stable version. You can find downloads at http://www.python.org/download/ I assume that you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=41&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Getting Django up and running on Windows is somewhat tricky. I used these instructions at our development department and publish these in hope that someone else can benefit of them too.</p>
<p>First thing is to download and install Python. I suggest using latest stable version. You can find downloads at <a href="http://www.python.org/download/">http://www.python.org/download/</a></p>
<p>I assume that you used standard c:\python26 as installation path from now on.</p>
<p>First, you need to add c:\python26\ and c:\python26\scripts\ to your path settings. Right click on Computer, select Properties. Select Advanced settings and then Advanced settings and click on Environment Variables. Depending on a case you add them to user (for you only) or to system (for all). If PATH variable exists, add those two mentioned paths to there, otherwise you need to create new variable named PATH. After adding and applying settings open new cmd console and check that path really has those newly added directories by typing SET PATH if you get paths listed you&#8217;re good to go. Note that setting environment varies a bit between different Windows versions.</p>
<p>Next you must install setuptools (a.k.a. easy_install) <a href="http://pypi.python.org/pypi/setuptools">http://pypi.python.org/pypi/setuptools</a>.</p>
<p>Now you can install Django very easily. Just type easy_install django and you get latest stable Django in no time installed.</p>
<p>Now, create first project somewhere in your development directories: django-admin.py startproject mytestproject</p>
<p>Go in newly created testproject directory, run manage.py runserver  and point your browser to <a href="http://localhost:8000/">http://localhost:8000/</a> You should see Django welcome screen.</p>
<p>If you encounter any errors, revise that you did all necessary steps.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/41/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/41/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/41/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=41&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2010/01/17/django-in-windows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
		<item>
		<title>Django JSON-RPC service</title>
		<link>http://drpinkpony.wordpress.com/2010/01/12/django-json-rpc-service/</link>
		<comments>http://drpinkpony.wordpress.com/2010/01/12/django-json-rpc-service/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 19:10:26 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[json-rpc]]></category>
		<category><![CDATA[rpc]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=38</guid>
		<description><![CDATA[Django and JSON-RPC. Originally this was presented at Django wiki, but contained lot of bugs. I fixed those and enhanced it for my personal use. So, not much to say, here&#8217;s the code itself. from django.db import transaction from django.utils.encoding import force_unicode from django.utils import datetime_safe from django.utils.functional import Promise import django.utils.simplejson as json import [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=38&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Django and JSON-RPC. Originally this was presented at Django wiki, but contained lot of bugs. I fixed those and enhanced it for my personal use.</p>
<p>So, not much to say, here&#8217;s the code itself.</p>
<pre class="brush: python;">
from django.db import transaction
from django.utils.encoding import force_unicode
from django.utils import datetime_safe
from django.utils.functional import Promise
import django.utils.simplejson as json
import datetime

class rpcmethod(object):
    def __init__(self, method):
        self.method = method

    def __call__(self, *args, **kwargs):
        return self.method(*args, **kwargs)

    def get_args(self, omittable=lambda m : m in ('self', 'request',)):
        from inspect import getargspec
        return [ a for a in getargspec(self.method).args if not omittable(a) ]

class NoSuchMethod(Exception):
    pass

class JsonRpc(object):
    &quot;&quot;&quot;
    JSON-RPC handler class for a view.

    Usage:

    def myview(request):
        rpc = JsonRpc( MyRpcClass() )
        result = rpc.handle_request(request)
        return HttpResponse(result)

    class MyRpcClass(object):
        url = reverse(myview)

        @rpcmethod
        def add(self, x, y):
            return x + y

    &quot;&quot;&quot;

    def __init__(self, instance, allow_errors=True, report_methods=True):
        self.instance = instance
        self.allow_errors = allow_errors
        self.report_methods = report_methods

        if not hasattr(self.instance, &quot;url&quot;):
            raise Exception(&quot;'url' not present in supplied instance&quot;)

    def get_public_methods(self):
        return [
            m for m in dir(self.instance) if getattr(self.instance, m).__class__ is rpcmethod
        ]

    def generate_smd(self):
        smd = {
                &quot;serviceType&quot;: &quot;JSON-RPC&quot;,
                &quot;serviceURL&quot;: self.instance.url,
                &quot;methods&quot;: []
        }

        if self.report_methods:
            smd[&quot;methods&quot;] = [
                {&quot;name&quot;: method, &quot;parameters&quot;: getattr(self.instance, method).get_args()} \
                for method in self.get_public_methods()
            ]

        return json.dumps(smd)

    def dispatch(self, method, params):
        if method in self.get_public_methods():
            return getattr(self.instance, method)(self.instance, *params)
        else:
            raise NoSuchMethod(method)

    def serialize(self, request):
        raw_request = json.loads(request.raw_post_data)
        request_id = raw_request.get(&quot;id&quot;, 0)
        request_method = raw_request.get(&quot;method&quot;)
        request_params = raw_request.get(&quot;params&quot;, [])

        response = {&quot;id&quot;: request_id}

        try:
            response[&quot;result&quot;] = self.dispatch(request_method, request_params)
        except Exception:
            # Fatal error
            if self.allow_errors:
                from traceback import format_exc
                response[&quot;error&quot;] = {
                        'type' : 'error',
                        'message' : &quot;%s&quot; % format_exc(),
                }
            else:
                response[&quot;error&quot;] = {
                        'type' : 'error',
                        'message': 'error',
                }

        # Rollback after failure
        if transaction.is_dirty():
            transaction.rollback()

        return json.dumps(response, cls=AugmentedJSONEncoder)

    def handle_request(self, request):
        if request.method == &quot;POST&quot; and len(request.POST) &gt; 0:
            return self.serialize(request)
        else:
            return self.generate_smd()

class AugmentedJSONEncoder(json.JSONEncoder):
    &quot;&quot;&quot;
    Augmentation for simplejson encoder.
    Now additionally encodes arbitrary iterables, class instances, decimals,
    lazy translations, dates, times and datetimes.
    &quot;&quot;&quot;

    DATE_FORMAT = &quot;%Y-%m-%d&quot;
    TIME_FORMAT = &quot;%H:%M:%S&quot;

    def default(self, o):
        if(hasattr(o, &quot;__iter__&quot;)):
            iterable = iter(o)
            return list(iterable)
        elif(hasattr(o, &quot;__add__&quot;) and hasattr(o, &quot;__sub__&quot;) and hasattr(o, &quot;__mul__&quot;)):
            return float(o)
        elif isinstance(o, datetime.datetime):
            d = datetime_safe.new_datetime(o)
            return d.isoformat()
        elif isinstance(o, datetime.date):
            d = datetime_safe.new_date(o)
            return d.strftime(self.DATE_FORMAT)
        elif isinstance(o, datetime.time):
            return o.strftime(self.TIME_FORMAT)
        elif isinstance(o, Promise):
            return force_unicode(o)
        elif(hasattr(o, &quot;__class__&quot;)):
            return o.__dict__
        else:
            return str(o)
</pre>
<p>On of the first questions might be, how to pass request object to my rpc method? Answer is simple &#8211; since your rpc class can have any kind of init with any kind of parameters, it&#8217;s more than natural to add request as one of the init parameters and add it to instance.</p>
<pre class="brush: python;">
def myview(request):
    rpc = JsonRpc( MyRpcClass(request) )
    result = rpc.handle_request(request)
    return HttpResponse(result)

 class MyRpcClass(object):
    url = reverse(myview)

    def __init__(self, request):
        self.request = request

    @rpcmethod
    def add(self, x, y):
        # Here you now have access to self.request
        return x + y
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/38/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/38/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=38&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2010/01/12/django-json-rpc-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
		<item>
		<title>Extension point for model</title>
		<link>http://drpinkpony.wordpress.com/2010/01/08/extension-point-for-model/</link>
		<comments>http://drpinkpony.wordpress.com/2010/01/08/extension-point-for-model/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 18:24:53 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Django]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=30</guid>
		<description><![CDATA[Sometimes there is a need to extend your model with arbitrary data. One good example is user profiles, data attached to your user model. I had a need of such system when creating application that was serves multiple customers. Each customer shares some common data between each other and then some of their own. To resolve [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=30&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Sometimes there is a need to extend your model with arbitrary data. One good example is user profiles, data attached to your user model.</p>
<p>I had a need of such system when creating application that was serves multiple customers. Each customer shares some common data between each other and then some of their own. To resolve my problem I loaned a piece from Django django.contrib.auth models and modified it a bit.</p>
<p>So define your model like this:</p>
<pre class="brush: python;">
from django.db import models

class MyExtensionNotAvailable(Exception):
    pass

class MyModel(models.Model):
# your common fields comes here

@property
def extension(self):
&quot;&quot;&quot;
Returns extension for this models. Raises
        MyExtensionNotAvailable if no extensions allowed.
        &quot;&quot;&quot;
        if not hasattr(self, '_ext_cache'):
            from django.conf import settings
            if not getattr(settings, 'MYMODEL_EXTENSION_MODEL'):
                raise MyExtensionNotAvailable
            try:
                app_label, model_name = settings. MYMODEL_EXTENSION_MODEL.split('.')
                model = models.get_model(app_label, model_name)
                self._ext_cache = model._default_manager.using(self._state.db).get(mymodel__id__exact=self.id)
                self._ext_cache.mymodel = self
            except (ImportError, ImproperlyConfigured):
                raise MyExtensionNotAvailable
        return self._ext_cache
</pre>
<p>Since extension is not created automatically when accessing extension creation must happen somehow. And here is where signals are very useful.</p>
<p>Add following code at the end of models.py. In real case you usually separate signal handling module. There you just make sure that you import your models inside handlers, otherwise you make circular imports and that&#8217;s something Python is not happy about.</p>
<pre class="brush: python;">
def post_mymodel_create(sender, **kwargs):
    if kwargs['created']:
        #from models import MyModelExtension
        MyModelExtension(mymodel=kwargs['instance']).save()

# Connect signal
django.db.signals.post_save.connect(post_mymodel_create, sender=MyModel)
</pre>
<p>Why signal? Because MyModel doesn&#8217;t have any more knowledge about your MyModelExtension than it has a field named &#8220;mymodel&#8221;. Rest is like a black box. That&#8217;s why you have to use signal. Signal handler knows all about your model and can populate all required fields with proper data.</p>
<p>To use extension is really simple, just create extension model, add field named &#8220;mymodel&#8221; to have foreign key (unique one) to MyModel. Then just point in settings MYMODEL_EXTENSION_MODEL parameter to your extension model and things get running:</p>
<pre class="brush: python;">
class MyModelExtension(models.Model):
    mymodel = models.ForeignKey(MyModel, unique=True)

    # Your fields here
</pre>
<p>And in settings.py you have to tell which model is your extension model: MYMODEL_EXTENSION_MODEL = &#8216;myapp.MyModelExtension&#8217;.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/30/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=30&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2010/01/08/extension-point-for-model/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
		<item>
		<title>Discriminator models</title>
		<link>http://drpinkpony.wordpress.com/2009/11/26/discriminator-models/</link>
		<comments>http://drpinkpony.wordpress.com/2009/11/26/discriminator-models/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 12:43:24 +0000</pubDate>
		<dc:creator>jtiai</dc:creator>
				<category><![CDATA[Django]]></category>

		<guid isPermaLink="false">http://drpinkpony.wordpress.com/?p=25</guid>
		<description><![CDATA[I recently came across of a need of models separated by discriminator. I have one lookup table that is split up in parts by using one value in one column. My original model was like: class LookupTable(models.Model): groupname = models.CharField(max_length=64) key = models.CharField(max_length=64) value = models.CharField(max_length=512) I had dozens of models pointing to this single [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=25&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I recently came across of a need of models separated by discriminator. I have one lookup table that is split up in parts by using one value in one column.</p>
<p>My original model was like:</p>
<pre class="brush: python;">
class LookupTable(models.Model):
    groupname = models.CharField(max_length=64)
    key = models.CharField(max_length=64)
    value = models.CharField(max_length=512)
</pre>
<p>I had dozens of models pointing to this single lookup table which was nightmare, specially with reverse relations. But I managed to figure one solution for this situation.</p>
<p>I used a custom save code, a custom manager and a magical proxy functionality in the Django. Let the code to speak for itself.</p>
<p>So here is my magical  GenericLookupManager</p>
<pre class="brush: python;">
class GenericLookupManager(models.Manager):
    def get_query_set(self):
        qs = super(GenericLookupManager, self).get_query_set()
        try:
            return qs.filter(groupname=self.model.GROUPNAME)
        except (ValueError, AttributeError):
            return qs
        return None
</pre>
<p>Enhanced LookupTable model</p>
<pre class="brush: python;">
class LookupTable(models.Model):
    groupname = models.CharField(max_length=64)
    key = models.CharField(max_length=64)
    value = models.CharField(max_length=512)

    objects = GenericLookupManager()

    def save(self, *args, **kwargs):
        try:
            self.groupname = self.GROUPNAME
        except (ValueError, AttributeError):
            pass # No GROUPNAME, pass

        super(LookupTable, self).save(*args, **kwargs)
</pre>
<p>And finally, how to use that model with proxying</p>
<pre class="brush: python;">
class UserType(LookupTable):
    GROUPNAME = 'USER_TYPE'

    class Meta:
        proxy = True
</pre>
<p>Now you can use proxied model to save, load and query it. Overridden LookupTable manager and save takes care that groupname is always taken into account.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/drpinkpony.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/drpinkpony.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/drpinkpony.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/drpinkpony.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/drpinkpony.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/drpinkpony.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/drpinkpony.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/drpinkpony.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/drpinkpony.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/drpinkpony.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/drpinkpony.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/drpinkpony.wordpress.com/25/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/drpinkpony.wordpress.com/25/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/drpinkpony.wordpress.com/25/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=drpinkpony.wordpress.com&amp;blog=10114370&amp;post=25&amp;subd=drpinkpony&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://drpinkpony.wordpress.com/2009/11/26/discriminator-models/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/dd6d5aa0e7a5a9c8218847074c1ac29d?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">jtiai</media:title>
		</media:content>
	</item>
	</channel>
</rss>
