<?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/"
	>

<channel>
	<title>Django &#8211; James Lin&#039;s Blog</title>
	<atom:link href="https://james.lin.net.nz/category/technology/programming/django/feed/" rel="self" type="application/rss+xml" />
	<link>https://james.lin.net.nz</link>
	<description>Just bits and pieces of my life</description>
	<lastBuildDate>Fri, 19 Jan 2018 22:42:50 +0000</lastBuildDate>
	<language>en-NZ</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.9.2</generator>
<site xmlns="com-wordpress:feed-additions:1">22801464</site>	<item>
		<title>Make sure you are closing the DB connections after accessing Django ORM in your threads</title>
		<link>https://james.lin.net.nz/2016/04/22/make-sure-you-are-closing-the-db-connections-after-accessing-django-orm-in-your-threads/</link>
		<comments>https://james.lin.net.nz/2016/04/22/make-sure-you-are-closing-the-db-connections-after-accessing-django-orm-in-your-threads/#respond</comments>
		<pubDate>Thu, 21 Apr 2016 21:07:47 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[concurrency]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[threads]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=3778</guid>
		<description><![CDATA[I was writing a service which import various feeds and then post to another RESTful API, simple enough as below: [crayon-5a65d676cceac675781535/] Then the feed model: [crayon-5a65d676cced5920262661/] Then run this feed in trivial code: [crayon-5a65d676ccee3756390441/] And you will quickly notice the threads complaining [crayon-5a65d676ccefb369741198/] What it&#8217;s happening is Django will create a new connection per thread… <span class="read-more"><a href="https://james.lin.net.nz/2016/04/22/make-sure-you-are-closing-the-db-connections-after-accessing-django-orm-in-your-threads/">Read More &#187;</a></span>]]></description>
				<content:encoded><![CDATA[<p>I was writing a service which import various feeds and then post to another RESTful API, simple enough as below:</p><pre class="crayon-plain-tag">from django.db import connections
class Receiver(PolymorphicModel):
    ...

class Database(Receiver):
    name = models.CharField(max_length=255)
    def get_data_source(self):
        return connections[name]</pre><p>Then the feed model:</p><pre class="crayon-plain-tag">class Feed(models.Model):
    receiver = models.ForeignKey('Receiver')

    def get_data_source(self):
        return self.receiver.get_real_instance().get_data_source()</pre><p>Then run this feed in trivial code:</p><pre class="crayon-plain-tag">import threading

function transform_listing(feed):
    cursor = feed.get_data_source().cursor()
    ....

feed = Feed.objects.create(receiver=Database.objects.create(name='legacy'))

for i in range(100):
    th = threading.Thread(transform_listing, [feed])
    th.start()</pre><p></p>
<p>And you will quickly notice the threads complaining </p><pre class="crayon-plain-tag">Too many connections</pre><p></p>
<p>What it&#8217;s happening is Django will create a new connection per thread when you access the ORM, and connections are left open even the threads are terminated, in this case the culprit is</p><pre class="crayon-plain-tag">def get_data_source(self):
        return self.receiver.get_real_instance().get_data_source()</pre><p></p>
<p>So in this case, simply refactor the code to close the connection before return:</p><pre class="crayon-plain-tag">from django.db import connection
...

    def get_data_source(self):
        result = self.receiver.get_real_instance().get_data_source()
        connection.close()
        return result</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2016/04/22/make-sure-you-are-closing-the-db-connections-after-accessing-django-orm-in-your-threads/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">3778</post-id>	</item>
		<item>
		<title>Laravel for Django developers, part 2</title>
		<link>https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-part-2/</link>
		<comments>https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-part-2/#respond</comments>
		<pubDate>Fri, 05 Feb 2016 00:43:07 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Laravel]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=3712</guid>
		<description><![CDATA[Global functions I am seeing a lot of framework specific global functions but don&#8217;t know where they come from, such as &#8220;view()&#8221;, &#8220;redirect()&#8221; etc etc. ORM Again, as mentioned in part 1, since we are creating migration files first, then we won&#8217;t be able to define FK relationships directly point to another model. According to… <span class="read-more"><a href="https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-part-2/">Read More &#187;</a></span>]]></description>
				<content:encoded><![CDATA[<h1>Global functions</h1>
<p>I am seeing a lot of framework specific global functions but don&#8217;t know where they come from, such as &#8220;view()&#8221;, &#8220;redirect()&#8221; etc etc.</p>
<h1>ORM</h1>
<p>Again, as mentioned in part 1, since we are creating migration files first, then we won&#8217;t be able to define FK relationships directly point to another model. According to the &#8220;<a href="https://laravel.com/docs/5.2/quickstart-intermediate#prepping-the-database">intermediate quickstart</a>&#8221; tutorial, you have to be a bit lower level like:</p><pre class="crayon-plain-tag">$table-&amp;gt;integer('user_id')-&amp;gt;index();</pre><p>Hang on&#8230; Would this create a FK constraint automatically like Django??</p>
<h1>Still ORM</h1>
<blockquote><p>Let&#8217;s add a few things to this model. First, we will state that the <code class=" language-php">name</code> attribute on the model should be &#8220;mass-assignable&#8221;. This will allow us to fill the <code class=" language-php">name</code> attribute when using Eloquent&#8217;s <code class=" language-php">create</code>method:</p></blockquote>
<p></p><pre class="crayon-plain-tag">class Task extends Model{
    protected $fillable = ['name'];
}</pre><p>Hmm, what? Skimming through the tutorial, so this enables you to do this:</p><pre class="crayon-plain-tag">$request-&amp;gt;user()-&amp;gt;tasks()-&amp;gt;create([
        'name' =&amp;gt; $request-&amp;gt;name,
    ]);</pre><p></p>
<h1>Still ORM &#8211; take 2</h1>
<p>In Django, when you define a ForeignKey like this</p>
<p></p><pre class="crayon-plain-tag">class User(models.Model):
  email = models.EmailField()

class Task(models.Model):
  user = models.ForeignKey(User, related_name=&quot;tasks&quot;)</pre><p></p>
<p>You can access the relationship in both ways automatically:</p><pre class="crayon-plain-tag">task.user
user.task_set.all()
user.tasks.all() // using optional defined related_name</pre><p></p>
<p>But in Laravel, it seems you have to define the relationship in each model.</p><pre class="crayon-plain-tag">class User extends Authenticatable
{
    // Other Eloquent Properties...

    /**
     * Get all of the tasks for the user.
     */
    public function tasks()
    {
        return $this-&gt;hasMany(Task::class);
    }
}

class Task extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name'];

    /**
     * Get the user that owns the task.
     */
    public function user()
    {
        return $this-&gt;belongsTo(User::class);
    }
}</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">3712</post-id>	</item>
		<item>
		<title>Laravel for Django developers, part 1</title>
		<link>https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-part-1/</link>
		<comments>https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-part-1/#respond</comments>
		<pubDate>Fri, 05 Feb 2016 00:05:27 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Laravel]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=3699</guid>
		<description><![CDATA[Project Structure After setting up the quickstart project, I feel the project structure is quite different to Django. In Django a lot of code are organised in &#8220;app&#8221; domain, but it seems to me that multi-app is not something out-of-the-box in Laravel: https://laracasts.com/discuss/channels/general-discussion/laravel-5-multi-app-or-modular-applications Instead, it seems the apps in Django is more similar to the… <span class="read-more"><a href="https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-part-1/">Read More &#187;</a></span>]]></description>
				<content:encoded><![CDATA[<h1>Project Structure</h1>
<p>After setting up the <a href="https://laravel.com/docs/5.2/quickstart" target="_blank">quickstart</a> project, I feel the project structure is quite different to Django. In Django a lot of code are organised in &#8220;app&#8221; domain, but it seems to me that multi-app is not something out-of-the-box in Laravel: <a href="https://laracasts.com/discuss/channels/general-discussion/laravel-5-multi-app-or-modular-applications">https://laracasts.com/discuss/channels/general-discussion/laravel-5-multi-app-or-modular-applications</a></p>
<p>Instead, it seems the apps in Django is more similar to the &#8220;Service Providers&#8221; in Laravel.</p>
<h1>ORM</h1>
<p>While working on the <a href="https://laravel.com/docs/5.2/quickstart" target="_blank">quickstart</a> project in Laravel, it seems to me that Eloquent doesn&#8217;t generate initial migratios based on model definition.</p>
<p>In Django, you define the model, then by running &#8220;makemigration&#8221; CLI command, it will generate initial migration files to create the database table for that model.</p>
<p>According to the quickstart project, it seems to be things work the other way around, you will have to manually create the migration files by running</p><pre class="crayon-plain-tag">php artisan make:migration create_tasks_table --create=tasks</pre><p>And then create the model class by running</p><pre class="crayon-plain-tag">php artisan make:model Task</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">3699</post-id>	</item>
		<item>
		<title>Laravel for Django Developers, prelude.</title>
		<link>https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-prelude/</link>
		<comments>https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-prelude/#respond</comments>
		<pubDate>Thu, 04 Feb 2016 23:56:58 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Laravel]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=3697</guid>
		<description><![CDATA[It appeared to me that &#8220;Laravel&#8221; is kind of similar to Django in the way of implementation concept, so this is my obvious choice. I did a google search &#8220;Laravel for Django developers&#8221; and got pretty much nothing useful, sure, who would have move back to PHP from Python? I think this only happens in… <span class="read-more"><a href="https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-prelude/">Read More &#187;</a></span>]]></description>
				<content:encoded><![CDATA[<p>It appeared to me that &#8220;Laravel&#8221; is kind of similar to Django in the way of implementation concept, so this is my obvious choice.</p>
<p>I did a google search &#8220;Laravel for Django developers&#8221; and got pretty much nothing useful, sure, who would have move back to PHP from Python? I think this only happens in New Zealand.</p>
<p>In the coming series, I will share my journey of learning Laravel, while comparing to Django, hopefully it will help out other Django developers like myself.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2016/02/05/laravel-for-django-developers-prelude/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">3697</post-id>	</item>
		<item>
		<title>A simple architecture to consolidate the realestate websites in NZ</title>
		<link>https://james.lin.net.nz/2015/12/07/a-simple-architecture-to-consolidate-the-realestate-websites-in-nz/</link>
		<comments>https://james.lin.net.nz/2015/12/07/a-simple-architecture-to-consolidate-the-realestate-websites-in-nz/#respond</comments>
		<pubDate>Mon, 07 Dec 2015 03:17:48 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Web Design]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=3607</guid>
		<description><![CDATA[Just a business idea, while I am browsing all these real estate websites, they pretty much give the same types of information, it could be reasonable profitable to consolidate the online platform, and even cheaper option for RE companies. I am not a sales person so I don&#8217;t know how to sell it, but it&#8217;s not… <span class="read-more"><a href="https://james.lin.net.nz/2015/12/07/a-simple-architecture-to-consolidate-the-realestate-websites-in-nz/">Read More &#187;</a></span>]]></description>
				<content:encoded><![CDATA[<p>Just a business idea, while I am browsing all these real estate websites, they pretty much give the same types of information, it could be reasonable profitable to consolidate the online platform, and even cheaper option for RE companies.</p>
<p>I am not a sales person so I don&#8217;t know how to sell it, but it&#8217;s not hard from a technical perspective to, let&#8217;s say consolidate all real estate websites in NZ into a platform.</p>
<p>If we look at all these real estate listings, they basically consisted with 2 models, the &#8220;listing&#8221; and &#8220;agent&#8221;. Having those 2 models stores 90% of the information needed. Surely we are not stopping at those 2 models, we will normalise the repetitive fields into models defined such as &#8220;location&#8221; , &#8220;company&#8221;(if we e want to have just one installation to serve multiple company websites&#8221;, etc etc. I think for implementing this is using Django, creating models is a breeze and using Django Rest Framework serving as APIs.</p>
<p>Slapping on a comprehensive search function using ElasticSearch, easy.</p>
<p>Since now we have a backend and communicating via API calls, then implementing the frontends is rather a freedom of choice for different companies. Lots of options (Django, NodeJS etc etc)</p>
<p>Side note:</p>
<p>These real estate companies will most probably have their own CRM systems, might be a bit of pain the implement the integration and probably having each installation for every company is a better choice.</p>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2015/12/07/a-simple-architecture-to-consolidate-the-realestate-websites-in-nz/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">3607</post-id>	</item>
		<item>
		<title>A very useful reference website if you use django class based views</title>
		<link>https://james.lin.net.nz/2014/10/30/a-very-useful-reference-website-if-you-use-django-class-based-views/</link>
		<comments>https://james.lin.net.nz/2014/10/30/a-very-useful-reference-website-if-you-use-django-class-based-views/#respond</comments>
		<pubDate>Wed, 29 Oct 2014 22:00:37 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[django]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=3548</guid>
		<description><![CDATA[A colleague of mine mentioned this site http://ccbv.co.uk/ which provides references and information about django class based views. Classy Class-Based Views. ccbv.co.uk The best way to understand Django&#8217;s class-based views is to see it in Classy CBV, so pick your version and jump in at the deep end.]]></description>
				<content:encoded><![CDATA[<div class="user-contributed">
<p class="discussion-body">A colleague of mine mentioned this site <a href="https://www.linkedin.com/redirect?url=http%3A%2F%2Fccbv%2Eco%2Euk%2F&amp;urlhash=lxw1&amp;_t=tracking_anet" target="blank" rel="nofollow">http://ccbv.co.uk/</a> which provides references and information about django class based views.</p>
</div>
<div class="referenced-item">
<div>
<h4 class="article-title"><a href="https://www.linkedin.com/redirect?url=http%3A%2F%2Fccbv%2Eco%2Euk%2F&amp;urlhash=lxw1" target="_blank">Classy Class-Based Views.</a> <span class="content-source">ccbv.co.uk</span></h4>
</div>
<p class="article-summary">The best way to understand Django&#8217;s class-based views is to see it in Classy CBV, so pick your version and jump in at the deep end.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2014/10/30/a-very-useful-reference-website-if-you-use-django-class-based-views/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">3548</post-id>	</item>
		<item>
		<title>Django should have OneToManyField</title>
		<link>https://james.lin.net.nz/2014/09/17/django-should-have-onetomanyfield/</link>
		<comments>https://james.lin.net.nz/2014/09/17/django-should-have-onetomanyfield/#comments</comments>
		<pubDate>Wed, 17 Sep 2014 02:07:08 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[onetomany]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=3537</guid>
		<description><![CDATA[A bit of background here about ForeignKey (many to one): If you have Order and OrderItem models, your order FK is in OrderItem model, from OrderItem model point of view, it&#8217;s Many OrderItem to One Order, in other words ManyToOne. What this implies is you need to have Order records before OrderItem records. Now, why… <span class="read-more"><a href="https://james.lin.net.nz/2014/09/17/django-should-have-onetomanyfield/">Read More &#187;</a></span>]]></description>
				<content:encoded><![CDATA[<p><strong>A bit of background here about ForeignKey (many to one):</strong></p>
<p>If you have Order and OrderItem models, your order FK is in OrderItem model, from OrderItem model point of view, it&#8217;s Many OrderItem to One Order, in other words ManyToOne. What this implies is you need to have Order records before OrderItem records.</p>
<p><strong>Now, why we need one to many:</strong></p>
<p>What if you have 2 different apps, say Settlement and Payment, which a payment can have multiple settlements, but settlements can only belong to one payment. Logically Payment app is built on top of Settlement app, in other words Settlement app doesn&#8217;t need to know about Payment app. But to make the constraint to work, you need to put the Payment foreignkey into the Settlement model (surely this makes sense in DB schema, but not in programming domain), which now Settlement app is required to know about the Payment app.</p>
<p>Not only the dependency is reversed, now you need to have payment record created before settlement record, WTF? Oh certainly you have the payment FK set to nullable, but then you will have an extra step to set the relationship.</p>
<p>Luckily there is a <a title="onetomany" href="https://github.com/adsworth/django-onetomany" target="_blank">3rd party package</a> that kind of solve this problem through ManyToMany relationship by adding unique constraint on the right hand column, but unluckily if you ever want to roll back to the normal ManyToManyField, the migration doesn&#8217;t remove the additional constraints that introduced by this package. See <a href="https://code.djangoproject.com/ticket/23498" target="_blank">django ticket</a>.</p>
<p>For relevant information:</p>
<p><a title="http://stackoverflow.com/questions/25635408/django-one-to-many-field-without-reversing-dependency" href="http://stackoverflow.com/questions/25635408/django-one-to-many-field-without-reversing-dependency" target="_blank">http://stackoverflow.com/questions/25635408/django-one-to-many-field-without-reversing-dependency</a></p>
<p><a title="http://blog.amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/" href="http://blog.amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/" target="_blank">http://blog.amir.rachum.com/blog/2013/06/15/a-case-for-a-onetomany-relationship-in-django/</a></p>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2014/09/17/django-should-have-onetomanyfield/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">3537</post-id>	</item>
		<item>
		<title>django-rest-framework: api versioning</title>
		<link>https://james.lin.net.nz/2014/02/18/django-rest-framework-api-versioning/</link>
		<comments>https://james.lin.net.nz/2014/02/18/django-rest-framework-api-versioning/#comments</comments>
		<pubDate>Tue, 18 Feb 2014 00:39:10 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[django-rest-framework]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=3485</guid>
		<description><![CDATA[Django Rest Framework is a very solid api framework, but it doesn&#8217;t provide out-of-box versioning mechanism, here is my attempt to implement version specific APIs. The goal is to achieve something like http://localhost:8000/api/(resource)/ http://localhost:8000/api/v1/(resource)/ plus allowing clients to specify the version in request header (X-Version), here is how we did it. Structure in side the… <span class="read-more"><a href="https://james.lin.net.nz/2014/02/18/django-rest-framework-api-versioning/">Read More &#187;</a></span>]]></description>
				<content:encoded><![CDATA[<p>Django Rest Framework is a very solid api framework, but it doesn&#8217;t provide out-of-box versioning mechanism, here is my attempt to implement version specific APIs.</p>
<p>The goal is to achieve something like</p>
<p><code><br />
http://localhost:8000/api/(resource)/<br />
http://localhost:8000/api/v1/(resource)/<br />
</code></p>
<p>plus allowing clients to specify the version in request header (X-Version), here is how we did it.</p>
<p><strong>Structure in side the API app:</strong></p>
<p><code><br />
├── __init__.py<br />
├── middlewares.py<br />
├── urls.py<br />
├── v1<br />
│   ├── __init__.py<br />
│   ├── account<br />
│   │   ├── __init__.py<br />
│   │   ├── serializers.py<br />
│   │   └── views.py<br />
│   └── urls.py<br />
└── v2<br />
    ├── __init__.py<br />
    ├── account<br />
    │   ├── __init__.py<br />
    │   ├── serializers.py<br />
    │   └── views.py<br />
    └── urls.py<br />
</code></p>
<p><strong>project urls.py:</strong></p>
<p></p><pre class="crayon-plain-tag">url(r'^api/', include('project.api.urls', namespace='api')),</pre><p></p>
<p><strong>api app level urls.py:</strong></p>
<p></p><pre class="crayon-plain-tag">from django.conf.urls import *

urlpatterns = patterns('',
    url(r'', include('project.api.v2.urls', namespace='default')),
    url(r'^v1/', include('project.api.v1.urls', namespace='v1')),
)</pre><p></p>
<p><strong>version level urls.py</strong></p>
<p></p><pre class="crayon-plain-tag">from django.conf.urls import *
from .account import views as account_views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('account', account_views.AccountView)
router.register('myaccount', account_views.MyAccountView)
urlpatterns = router.urls</pre><p></p>
<p>create a middleware to switch to the correct code by changing the path_info, please note there is a caveat that namespace (&#8216;api&#8217;) defined in project level urls is not flexible and needs to be known in middleware:</p>
<p></p><pre class="crayon-plain-tag">from django.core.urlresolvers import resolve
from django.core.urlresolvers import reverse


class VersionSwitch(object):

def process_request(self, request):
    r = resolve(request.path_info)
    version = request.META.get('HTTP_X_VERSION', False)
    if r.namespace.startswith('api:') and version:
        old_version = r.namespace.split(':')[-1]
        request.path_info = reverse('{}:{}'.format(r.namespace.replace(old_version, version), r.url_name), args=r.args, kwargs=r.kwargs)</pre><p></p>
<p>Sample url:</p>
<p></p><pre class="crayon-plain-tag">curl -H &quot;X-Version: v1&quot; http://your.domain:8000/api/myaccount/</pre><p></p>
<p>My original <a href="http://stackoverflow.com/questions/14269719/django-rest-framework-api-versioning/21839842#21839842" title="django-rest-framework versioning" target="_blank">answer</a> on stackoverflow.</p>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2014/02/18/django-rest-framework-api-versioning/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">3485</post-id>	</item>
		<item>
		<title>Django CMS Haystack 2.0 Search Index</title>
		<link>https://james.lin.net.nz/2013/11/06/django-cms-haystack-2-0-search-index/</link>
		<comments>https://james.lin.net.nz/2013/11/06/django-cms-haystack-2-0-search-index/#comments</comments>
		<pubDate>Wed, 06 Nov 2013 07:13:43 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[django-cms]]></category>
		<category><![CDATA[haystack]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=3448</guid>
		<description><![CDATA[Currently django-cms-search doesn&#8217;t support haystack 2.0 yet, so here is my modified version to work on haystack 2.0 based on [crayon-5a65d676d1a10886534604/]]]></description>
				<content:encoded><![CDATA[<p>Currently django-cms-search doesn&#8217;t support haystack 2.0 yet, so here is my modified version to work on haystack 2.0 based on <a href="http://django-cms.readthedocs.org/en/2.1.3/extending_cms/searchdocs.html#id1" title="django cms documentation" target="_blank"></a></p>
<p></p><pre class="crayon-plain-tag">import datetime
from haystack import indexes   
from cms.models.managers import PageManager
from cms.models.pagemodel import Page
from cms.models.pluginmodel import CMSPlugin


class PageIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=False)
    pub_date = indexes.DateTimeField(model_attr='publication_date', null=True)
    login_required = indexes.BooleanField(model_attr='login_required')
    url = indexes.CharField(model_attr='get_absolute_url')
    title = indexes.CharField(model_attr='get_title')

    def prepare(self, obj):    
        self.prepared_data = super(PageIndex, self).prepare(obj)
        plugins = CMSPlugin.objects.filter(placeholder__in=obj.placeholders.all())
        text = ''              
        for plugin in plugins: 
            instance, _ = plugin.get_plugin_instance()
            if hasattr(instance, 'search_fields'):
                text += ''.join(getattr(instance, field) for field in instance.search_fields)
        text += obj.get_meta_description() or u''
        text += obj.get_title() or u''
        text += obj.get_meta_keywords() if hasattr(obj, 'get_meta_keywords') and obj.get_meta_keywords() else u''
        self.prepared_data['text'] = text
        return self.prepared_data       

    def get_model(self):
        return Page

    def index_queryset(self, using=None):
        return Page.objects.published().filter(publisher_is_draft=False).distinct()</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2013/11/06/django-cms-haystack-2-0-search-index/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">3448</post-id>	</item>
		<item>
		<title>Django admin UnicodeEncodeError</title>
		<link>https://james.lin.net.nz/2013/06/19/django-admin-unicodeencodeerror/</link>
		<comments>https://james.lin.net.nz/2013/06/19/django-admin-unicodeencodeerror/#respond</comments>
		<pubDate>Tue, 18 Jun 2013 21:59:24 +0000</pubDate>
		<dc:creator><![CDATA[James Lin]]></dc:creator>
				<category><![CDATA[Django]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[unicode]]></category>

		<guid isPermaLink="false">http://james.lin.net.nz/?p=1466</guid>
		<description><![CDATA[Don&#8217;t we all get confused by unicode encoding sometimes? Especially you wouldn&#8217;t expect this kind of error to happen in django admin. The problem is actually not in the admin section, the culprit is __unicode__ method in your model. when you have a unicode function like this: [crayon-5a65d676d4860104864106/] It is actually returning a ASCII string(which… <span class="read-more"><a href="https://james.lin.net.nz/2013/06/19/django-admin-unicodeencodeerror/">Read More &#187;</a></span>]]></description>
				<content:encoded><![CDATA[<p>Don&#8217;t we all get confused by unicode encoding sometimes? Especially you wouldn&#8217;t expect this kind of error to happen in django admin. The problem is actually not in the admin section, the culprit is __unicode__ method in your model.</p>
<p>when you have a unicode function like this:</p>
<p></p><pre class="crayon-plain-tag">def __unicode__(self):
  return &quot;{0}&quot;.format(self.field_one)</pre><p></p>
<p>It is actually returning a ASCII string(which means, it will try to convert field_one to ASCII), if the field_one contains characters outside of ASCII, you will get the problem as above.</p>
<p>Now consider this unicode function:</p>
<p></p><pre class="crayon-plain-tag">def __unicode__(self):
      return self.field_one</pre><p></p>
<p>This works fine, because you are returning unicode string directly, no conversion needed.</p>
<p>Lets revisit the first unicode function, to make it work, you just need to add u to make it a unicode string</p>
<p></p><pre class="crayon-plain-tag">def __unicode__(self):
      return u&quot;{0}&quot;.format(self.field_one)</pre><p></p>
]]></content:encoded>
			<wfw:commentRss>https://james.lin.net.nz/2013/06/19/django-admin-unicodeencodeerror/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<post-id xmlns="com-wordpress:feed-additions:1">1466</post-id>	</item>
	</channel>
</rss>
