<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Passing Curiosity: Posts tagged django</title>
    <link href="https://passingcuriosity.com/tags/django/django.xml" rel="self" />
    <link href="https://passingcuriosity.com" />
    <id>https://passingcuriosity.com/tags/django/django.xml</id>
    <author>
        <name>Thomas Sutton</name>
        
        <email>me@thomas-sutton.id.au</email>
        
    </author>
    <updated>2013-07-05T00:00:00Z</updated>
    <entry>
    <title>DjangoConAU 2013</title>
    <link href="https://passingcuriosity.com/2013/pyconau-and-djangoconau/" />
    <id>https://passingcuriosity.com/2013/pyconau-and-djangoconau/</id>
    <published>2013-07-05T00:00:00Z</published>
    <updated>2013-07-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’m attending <a href="http://www.djangocon.com.au/">DjangoConAU</a> 2013 (I believe this is the inaugural DjangoCon
Australia) today and PyCon Australia tomorrow. If last year is any guide, it’s
going to be a pretty awesome weekend! I’ll try to update this post over the
course of the day. Not real live blogging, more delayed telecast blogging.</p>
<p>Also: these are notes I’m typing during the sessions. They are probably errors
and such. I’ll come back and tidy them up later. Maybe.</p>
<p><a href="http://teespring.com/dcau2013">DjangoCon Australia 2013 t-shirt</a></p>
<h2 id="alex-gaynor-on-the-divided-web-and-the-role-of-frameworks">Alex Gaynor on the Divided Web and the Role of Frameworks</h2>
<p><a href="http://2013.pycon-au.org/programme/miniconfs/djangocon#gaynor">Alex Gaynor on the Divided Web and the Role of Frameworks</a>
(<a href="https://speakerdeck.com/alex/a-divided-web-and-the-role-of-frameworks">slides</a>). First person to have spoken at DjangoCons on three
continents (for a hour or two).</p>
<p>History of the web: the big bang, ENIAC, Apple II, T.B.L. and Mosaic.</p>
<p>Email and FTP are more applications, but the web technologies (HTML, HTTP,
etc.) are, effectively, platforms: they don’t have any specific thing you do
with them, you do what you like.</p>
<ol type="1">
<li><p>Static content. In vim or something.</p></li>
<li><p>Dynamic content.</p></li>
<li><p>DHTML - nothing good came of this.</p></li>
<li><p>Microsoft invented AJAX (with ActiveX controls).</p></li>
<li><p>“Web 2.0” is what we think “web applicaiton” means these days.</p></li>
</ol>
<p>Frameworks are being release (RoR &amp; Django; see the Snakes and Rubies). These
made lots of stuff that was a pain (“database driven applications”) more
convenient.</p>
<p>Most people land on one side or the other, but current practice seems to have
landed on “both”: backend and frontend are both getting more and more complex.</p>
<p>Technologies are living longer: some of this stuff is likely to be the COBOL of
the future.</p>
<p>All these new tools and technologies don’t create new capabilities, they make
existing capabilities more convenient to manage and to use. Rails and Django to
let you do something new.</p>
<p>Django was designed to allow small groups of people to build complex “web
applications” quickly. It still solves the same problem in 2013 as it did in
2005.</p>
<p>In 2009 there were a few more things that were though required: monitoring,
message quues, APIs, workers, search indexing. Django has nothing to say about
any of these (though many of them are addressed by third-party apps and
external packages).</p>
<p>In 2013 you need deployment, configuration management, to think about SOA,
real-time stuff (Websockets, etc.) and the crazy, crazy world of front-end
Javascript.</p>
<p>We’re building more and more platforms for specific use cases.</p>
<p>In spite of all these new frameworks and tools addressing parts of a puzzle,
nothing has really encroached on Django and Rails yet. Either Django will start
addressing some of these cases or it’ll be made obsolete by something better.</p>
<blockquote>
<p>Everything is getting more complex and bigger.</p>
</blockquote>
<p>Deployment has always sucked but Alex has reason to believe that there is a
bright future.</p>
<ul>
<li>Applications in <a href="http://www.docker.io/">Docker</a> containers.</li>
</ul>
<ul>
<li>Servers configured with Chef &amp; <a href="https://wiki.openstack.org/wiki/Heat">Heat</a> (orchestration as a service; part of
OpenStack?) which run your containers.</li>
</ul>
<p>Most full-service cloud platforms include some sort of orchestration tool
(Heat, CloudFormation).</p>
<p>The “divide” of the title comes in a number of axes:</p>
<ul>
<li>small and big teams</li>
<li>contractors and in-house</li>
<li>“sites” and “apps”</li>
</ul>
<p>The increase in complexity seems to be favouring one side of each divide. “The
ink is never dry”.</p>
<h3 id="qa">Q&amp;A</h3>
<p>Where does Django fit in a world which almost forces us to work in (or, at
least, interoperate with JS)?</p>
<blockquote>
<p>DHH’s comment on Rails’ JS helpers: “Yes, JS is horrible.” Google is
trying something interesting with Dart. It’s probably not particularly
feasible to implement Python on top of JS (like the Dart compat).</p>
<p>“Best viewed in Chrome” must never come back.</p>
</blockquote>
<h2 id="jacob-kaplan-moss-on-porting-django-apps-to-python-3">Jacob Kaplan-Moss on Porting Django apps to Python 3</h2>
<blockquote>
<p>Hey y’all</p>
</blockquote>
<p>Django 1.5 supports Python 3, in Django 1.6 it’s considered stable. So let’s
all use it.</p>
<p>First question is: whether we should use Python 3? The answer is yes. Python 3
is Python with “30% fewer warts”. Biggest improvement is that Unicode really
works.</p>
<p>Second question is: can we use Python 3? This is essentially a question of your
application’s dependencies and whether they’ve been ported yet.</p>
<p>Problems:</p>
<ul>
<li><p>First big problem is choice ot DB. If you use Postgres you’re fine. SQLite
works. MySQL has a connector (but there are licensing concerns, so the
foundation can’t recommend it). You should be using Postgres.</p></li>
<li><p>Second big problem is your server/deployment software: modwsgi, uWSGI and
synchronous gunicorn are all fine. gunicorn async is problematic (due to
gevent). You may need to switch deployment and operation strategy.</p></li>
<li><p>South, Celery, Raven (sentry), django-extensions, all work. But not
django-compressor, django-tagging (last update 2009), django-social-auth,
django-debug-toolbar, Haystack. But there are suitable alternatives to these
(django-pipeline, django-auth, <a href="https://pypi.python.org/pypi/django-taggit">django-taggit</a>).</p></li>
</ul>
<p>Every time working with Python 3 Jacob has had to play this game evaluating
apps and libraries for Python 3 support.</p>
<p>Third question is: should I use Python 3? This can be complicated, with the
additional costs of learning the new stuff, re-/evaluating apps and libraries
for Python 3 support. Perhaps the best advice is to use Python 3 if you can and
Python 2 if you must; Python 3 will be improved, get faster, etc. There’s no
future for Python 2 (possibly decades, but still; RedHat have committed to
supporting it for 2030 or something).</p>
<h3 id="how-do-i-use-python-3">How do I use Python 3?</h3>
<p>If you can, support only Python 3. It’s not too hard to add support for Python
2 later if it becomes necessary during the development process.</p>
<p>Python 3 introduced a tool called <code>2to3</code> which converts Python 2 code for
Python 3 (by doing AST transformations and generating a patch). The Python 3
code being generated, makes it very hard to fix bugs and makes community
contribution very hard.</p>
<p>The “single source” approach is much better: write Python 3 code and include
shims to paper over the deficits when run under Python 2. If you have to
support Python 2 you should be using this technique.</p>
<ol start="3" type="1">
<li><p>Supporting both Python 2 and Python 3 <em>requires</em> automated testing. You
can’t hope to maintain it without continuous integration.</p></li>
<li><p>Fix all the unicode handling issues that your test suite identifies. There
will be lots.</p></li>
<li><p>Iterate on test failures.</p></li>
</ol>
<h3 id="case-study-python.org">Case Study: python.org</h3>
<p>Decided to support only Python 3.3+ (if possible). Left single-source open if
it became necessary later.</p>
<p>Dependencies:</p>
<ul>
<li><p>Light CMS requirements. None of the existing CMS packages supported Python 3
yet, decided to build it as the requirements were so simple.</p></li>
<li><p>Quite complex and specific user, permissions and authentication requirements,
so none of the apps would have been applicable anyway.</p></li>
<li><p>Heavy integration with social media services. None of the social login tools
(which they evaluated) had been ported at the time, so they moved on to other
features and bugged the maintainers to port (and it worked).</p></li>
<li><p>Moderate traffic requirements with extreme spikes related to releases, etc.</p></li>
<li><p>Testing: django-discover-runner works fine on Python 3 (and is, essentially,
included in Django 1.6).</p></li>
<li><p>The hardest part of the process was “retraining our unicode three muscles to
do things the Python 3 way”.</p>
<blockquote>
<p>The biggest thing you can do is eliminate the word “string” from your
vocabulary. Bytes are just bytes, text is text.</p>
</blockquote>
<p><code>django.utils.encoding</code> does this.</p></li>
</ul>
<p>It worked and it’ll be launching in about a month (hopefully).</p>
<p>They estimate the project cost about 20% more to develop, mostly in terms of
increased development time. In large part, most of this time is probably just
changing maintenance costs into upfront costs. And the number is probably
smaller now.</p>
<h3 id="case-study-django-sitetree">Case study: django-sitetree</h3>
<p>Django application for managing a hierarchical navigation tree. Ported by Jeff
Triplett in <a href="https://github.com/idlesign/django-sitetree/commit/c7475">a single commit</a>.</p>
<p>Shared source approach with: Python 2.6+, Python 3.3+; Django 1.4+. This is a
reasonable set of minimum requirements.</p>
<p>There aren’t any dependencies. If your app has dependencies, you may need to
port them too!</p>
<p>Using <a href="http://tox.readthedocs.org">Tox</a> to run test suite in multiple environments. You’ll pick up a
bunch of syntax issues with the changes in Python 3.</p>
<p>Django adds the <code>@python_2_unicode_compat</code> decorator to change <code>__unicode__</code>
into <code>__str__</code> if running on Python 2.</p>
<p><a href="http://pythonhosted.org/six/">Six</a> (included in <code>django.utils.six</code>) helps to
paper over some of the differences (metaclasses, type names of byte and text
types, etc.)</p>
<p>There’s a <a href="http://django.me/py3">guide for porting to Python 3</a> with detailed documentation.</p>
<p>Python 3 is ready, the WSGI containers are ported, the databases are ported,
the frameworks are ported. Now it’s up to the community to port the libraries
and applications.</p>
<h3 id="qa-1">Q&amp;A</h3>
<p>Is <code>from future import unicode</code> a good idea?</p>
<blockquote>
<p>Unicode literals aren’t a thing in Python 3, but using stuff from future is probably a good idea.</p>
</blockquote>
<h2 id="greg-turner-on-using-feincms">Greg Turner on using FeinCMS</h2>
<p>Greg is the filling in a core-contributor sandwich.</p>
<p>The web and web-content are becoming more complex: there are more technologies,
more devices, users expect richer experiences. See <a href="http://www.nytimes.com/projects/2012/snow-fall/">NYT Snowfall</a> for an
example. Teams are getting smaller and smaller (economics, etc.) We need to
build content which is future-proof, cross platform, clean and semantic.</p>
<p>These are the problems that <a href="http://www.feincms.org/">FeinCMS</a> attempts to solve. A document (page)
combines a services of lumps of content (content types, not the same thing as
Django content types).</p>
<p>See the [MCA site][].</p>
<p>FeinCMS provides a model and admin to use as a base in your own app. This
allows site admins to combine and embed different types of content in their
documents (instances of your FeinCMS models).</p>
<p>Each model has specific set of content types which are supported. This is kind
of ugly, <a href="http://github.com/ixc/glamkit-feincmstools">FeinCMStools</a> makes it nicer. He’s made a <a href="https://github.com/ixc/feincmstools-demo">demonstration</a>
(see the tags).</p>
<ol type="1">
<li><p>Define the regions in your content type. https://github.com/ixc/feincmstools-demo/blob/master/djangosite/meetups/models.py#L17</p></li>
<li><p>Define content types which can go in your regions. https://github.com/ixc/feincmstools-demo/blob/master/djangosite/meetups/models.py#L23</p></li>
<li><p>There are lots of tables, so make sure you’re careful with migrations, etc.</p></li>
</ol>
<p>Content types don’t have to be content. Example of a content type, which offers
the site admin a choice of layouts which have been designed and built ready for
them to use.</p>
<h3 id="qa-2">Q&amp;A</h3>
<p>How does FeinCMS handle structured content?</p>
<blockquote>
<p>They are just normal Django models, so they can be as structured and semantic as you like.</p>
</blockquote>
<p>FeinCMS uses Django admin which some users dislike. Any tips on making it nicer?</p>
<blockquote>
<p>Not really. But they use <code>django-admintools</code>. Would like to see a
more heterogenous approach to admin, which many other CMS support and
which better maps to user expectations.</p>
</blockquote>
<h2 id="russell-keith-magee-on-secrets-of-the-testing-masters">Russell Keith-Magee on Secrets of the Testing Masters</h2>
<p>CTO of TradesCloud. Hiring soon if you want to move to Perth.</p>
<p>Testing is good and we should all be doing it. As we all know. First
contribution to django was adding app testing. It has lots of support for
testing contrib, but not everything. Introducing two testing tools which are
helpful and good and such.</p>
<h3 id="problem-you-need-test-data">Problem: You need test data</h3>
<p>Django’s testing framework supports fixtures (declared in test case class).
Fixtures are easy to create, but hard to read, hard to update and include no
documentation. Also include a lot of rubbish which isn’t relevant to the test
(1 line out of 18 when testing “admin can X”). You need to <em>know</em> that user 23
is the “staff user with no existing content”.</p>
<p>Solution is <code>factory_boy</code>: an EDSL for creating test objects in your tests,
programmatically.</p>
<p>You create factory classes for your models. Provide place holder values, use
helpers to generate values (sequences for unique email addresses, lazy values
which are calculated late in the process).</p>
<p>Subfactories all you to create child objects. E.g. BlogPost factory has User
sub-factory for the post author. Can still be overridden on specific cases when
tests require. This overriding can traverse joins just like Django model stuff:
<code>PostF(author__firstname='thomas')</code></p>
<p>Lets you access and override various bits of instance data and the creation
process.</p>
<p>Factory-boy also supports: SQLAlchemy and Mogo.</p>
<p>There’s also a django-factory-boy package which includes pre-defined factories
for Django modules.</p>
<h3 id="problem-youre-dependant-on-an-external-service">Problem: You’re dependant on an external service</h3>
<p>Any external services that you use – payment processing, social networks, etc.
– will affect your ability to test. You might also have trouble testing your
failure cases.</p>
<p>Any internal services might be slow, unreliable or difficult to configure.
Things like deliberately slow password hashing, database failure, etc.</p>
<p>You can just ignore this and not test those bits.</p>
<p>You can use <code>mock</code> (Python 3.3 stdlib <code>unittest.mock</code>, installable on Python
2.7+); essentially organised monkeypatching.</p>
<ul>
<li><p>Mock object which provides pre-defined return values.</p></li>
<li><p><code>@patch</code> decorators to inject mock objects into an existing API.</p></li>
</ul>
<p>Mock instances track how they are used, allowing you to assert various
properties about the way your code is used.</p>
<pre><code>obj = SomeObject()
obj.method = Mock(return_value=3)
obj.method.assert_...</code></pre>
<p><code>@patch</code> allows you to use a function (the decorated function) to replace an
existing function.</p>
<p>There are other similar packages, but Russell likes sticking with the standard
library unless really required.</p>
<p>PS: There will be an announcement during Russell’s PyCon talk.</p>
<h2 id="simon-meers-on-django-unstrained">Simon Meers on Django Unstrained</h2>
<p>Simon (DrMeers online) is part of the Django core team, having discovered
Django in 2008. Lots of clients with deadlines.</p>
<p>Django (like all real Open Source projects) is <em>our</em> framework, it’s up to us
to improve it. We probably want to avoid adding more functionality to Django
core, but helping it to evolve to be an [even more] flexible platform for
third-party contribution. Rich third-party eco-system.</p>
<ul>
<li><p><a href="https://github.com/pennersr/django-allauth">django-allauth</a></p></li>
<li><p><a href="https://github.com/brack3t/django-braces">django-braces</a></p></li>
<li><p><code>django-generic</code> containing snippets and patterns which you use over and over
again. Simon’s snippets package is on <a href="http://bitbucket.org/DrMeers">his BitBucket account</a>.</p></li>
</ul>
<ul>
<li><p><a href="https://pypi.python.org/pypi/django-import-export">django-import-export</a> for
CSV, etc.</p></li>
<li><p>Nested inline forms has been discussed in tickets.</p></li>
<li><p>Floppy forms and Crispy forms improve</p></li>
<li><p>Pass through manager just passes things through to the underlying queryset?
This is something I could have used before.</p></li>
</ul>
<p><a href="http://github.com/DrMeers/">Simon’s Github account</a> will contain the slides at
some point.</p>
<h2 id="tom-eastman-on-the-coolest-parts-of-backend-development-with-django">Tom Eastman on the coolest parts of backend development with Django</h2>
<p>Catalyst IT (in Wellington) have a growing Django team. Come talk to Tom if you
might be interested in moving.</p>
<p>Large, reasonably high profile project for the Department of Education.</p>
<ul>
<li>AngularJS, D3, Compass/SASS for frontend.</li>
<li>Django, gunicorn, tastypie, celery and south.</li>
</ul>
<p>Working in a large team means that back end developers can avoid front-end
stuff like browser quirks, etc. The job then has only three parts:</p>
<ul>
<li>Make it <em>correct</em></li>
<li>Make it <em>fast</em></li>
<li>Make it <em>secure</em></li>
</ul>
<h3 id="correct">Correct</h3>
<blockquote>
<p>Code without tests is broken by design.</p>
</blockquote>
<p>And</p>
<blockquote>
<p>The converse of test-driven development is faith-based development.</p>
</blockquote>
<p>Your tests should be run regularly. Using a tool based on things like <code>inotify</code>
allow you to see test results as you work.</p>
<p><em>You must see your tests fail before they pass.</em> Without this, you can’t tell
that your code makes the test pass. Either the code is wrong or the tests are
wrong.</p>
<p><em>Testing errors is more important than testing the happy case.</em> It’s unusual
for people to test error cases (only usually when the errors occur during
development). Write test cases which cover error cases.</p>
<p>Django gives you all the tools you need to test the things you need to test,
and do it properly.</p>
<p>Continous integration and rigours code review are two of the best inventions
ever. Tools like Jenkins and Gerrit make these reasonably easy to setup.</p>
<p>Took three tries to get integration testing to work:</p>
<ol type="1">
<li><p>Using the Selenium recorder. It generated hideous, unmaintainable code and
gave up.</p></li>
<li><p>PhantomJS is headless webkit controlable with JS. It shows promise but was
rather unstable.</p></li>
<li><p>Went back to Selenium having learned how to split tests from page
controllers (see <a href="http://hedleyproctor.com/2012/07/effective-selenium-testing/">Effective Selenium testing</a>). This makes it easy to
maintain tests when pages change, etc.</p></li>
</ol>
<h3 id="fast">Fast</h3>
<p>Varnish and CDNs are all fun, but can be difficult on sites that contain
non-public information, freshness requirements, etc. How do you keep your web
site fast without public caching?</p>
<p>Using etag and last-modified headers in Django. Use auto-updating timestamps in
models; with appropriate indexes in the database, it can be very fast to check
last-modified headers. Takes more DB queries to check freshness, but is almost
always a speedup; an example view takes 800ms to generate the full response vs
50ms to check modification.</p>
<ol type="1">
<li>Check authorisation.</li>
<li>If the etag matches, yay!</li>
<li>With no etag, serve from cache.</li>
<li>Generate (and cache) the page. (Invalidate cache on saves).</li>
</ol>
<h3 id="secure">Secure</h3>
<p>If you, as a web developer, haven’t read the OWASP Top 10 then you are a
liability to every site you work on.</p>
<p>Things that seem innocuous – processing XML from clients – are often unsafe.
Disable functionality that you don’t need: XML, YAML, etc.</p>
<p>If your site requires logins then your site requires SSL. See Firesheep if you
haven’t seen it.</p>
<p>Django forms are for validating import; not just generating HTML forms. Use
them for everything! Query strings, CSV records, etc. Even if you don’t (yet)
have any rules to enforce, create a form so you’ll have somewhere to put it.</p>
<p>Django can’t protect you if you don’t let it. If you bypass the ORM, then it’s
<strong>your</strong> job to handle SQL injection. If you bypass the template language, then
it’s <strong>your</strong> job to validate.</p>
<p>Annoy your pentester so they <em>really</em> want to find your bugs. Current project
has sent 18,000 emails about 500 errors.</p>
<h3 id="qa-3">Q&amp;A</h3>
<p>Adding tests to a codebase without them?</p>
<blockquote>
<p>You need to be able to put your database into a known state for
testing purposes. Doing smoke test (is it all 200 OK?) are quick and
easy. Unit tests can be easy to start.</p>
</blockquote>
<p>What are the most common issues found in code review?</p>
<blockquote>
<p>Silly mistakes. Often, the review comment is “why wasn’t this
tested?” Often it helps share knowledge about better ways, etc.
throughout the whole team, to notice additional cases which need
testing, etc.</p>
<p>If nothing else, it helps to make sure that the whole team knows about
the code base.</p>
</blockquote>
<h2 id="curtis-maloney-on-a-state-of-rest">Curtis Maloney on A state of REST</h2>
<p>Curtis is responsible for:</p>
<ul>
<li>django-nap</li>
<li>django-rated</li>
</ul>
<p>Everyone who doesn’t hangout on irc://freenode.net#django is missing out.</p>
<p>Django doesn’t really have any REST frameworks; the API frameworks we have
are pretty useful and kinda REST-y, though.</p>
<ul>
<li><p>TastyPie</p></li>
<li><p>Django REST Framework</p></li>
<li><p>django-nap tries to make a faster, smaller TastyPie.</p></li>
</ul>
<p>There are a bunch of features for an API frameworks. Let’s look at a few of
them.</p>
<h3 id="auth">Auth</h3>
<p>Authentication – identifying the user – and authorisation – deciding whether
the user can perform the operation.</p>
<p>TastyPie and DRF both include support for a bunch of authentication approaches.
NAP makes/allows you to do it yourself using existing tools.</p>
<p>See the “Fuck OAuth 2 video”.</p>
<p>Both TastyPie and DRF include their own functionality; NAP allows you to
provide a callback.</p>
<h3 id="data-formats">Data Formats</h3>
<p>TastyPie and DRF both support many frameworks.</p>
<p>NAP supports a few, but only one at a time?</p>
<h3 id="serialisation">Serialisation</h3>
<h3 id="shapes">Shapes</h3>
<p>TastyPie lets you define per-field visibility (list vs details)</p>
<p>NAP (and DRF?) you can specify it per-view.</p>
<h3 id="pagination">Pagination</h3>
<p>TP: Custom class, offset and limit</p>
<p>DRF: django native pagination. page and size.</p>
<p>NAT: django native pagination. Page with size or offset with limit.</p>
<p>Pagination has security implications, unlimited page sizes can allow denial of
service.</p>
<h3 id="rate-limiting">Rate limiting</h3>
<p>Both TastyPie and DRF have their own rate limiting implementations.</p>
<p>NAT doesn’t, because it’s a separate concern (in django-rated).</p>
<h3 id="filtering">Filtering</h3>
<p>Django ORM filtering is important, but a whitelist is important (don’t let
people tranverse links).</p>
<h3 id="versioning">Versioning</h3>
<p>TastyPie: ?</p>
<p>DRF: Viewset (collection of views for responding to HTTP verbs for a collection
of resources) with routing.</p>
<p>NAP: collect a bunch of Publishers into a version.</p>
<h3 id="generic-views">Generic Views</h3>
<p>Can be clumsy to reuse TastyPie resources in your own views.</p>
<p>DRF is built on the generic views approach. It’s the first step in the tutorial.</p>
<p>Using HTTP responses which are also exceptions. So you can produce</p>
<h3 id="overview">Overview</h3>
<p>TastyPie is a very quick way to expose a model as an API, but going further
means learning a lot about it’s APIs and internals.</p>
<p>In compiling the talk, started to doubt continuing NAP at all because DRF is
pretty awesome.</p>
<h2 id="core-developer-panel">Core Developer Panel</h2>
<p>Russell, Chris, JKM, Alex &amp; Simon; moderated by Greg.</p>
<h3 id="whats-the-best-and-worst-things-about-it">What’s the best and worst things about it?</h3>
<p>Russell: The fact that it happens at all is pretty wonderful; but there’s so
much more we could/should be doing.</p>
<p>Jacob: Watching people get into Python because of Django; the expectation was
that it’d see a little takeup from newspaper people and a few who already know
Python, seeing half a room say they learned the language because of Django is
amazing. The idea that some people consider themselves Django developers (and
not Python developers) is somewhat disheartening.</p>
<h3 id="are-their-situations-in-which-you-dont-use-django">Are their situations in which you don’t use Django?</h3>
<p>Alex: Doesn’t use Django much at all in his current role.</p>
<p>Chris: Not much, mostly when required.</p>
<h3 id="streamline-vs-bloat">Streamline vs bloat</h3>
<p>Simon: Core should really, really be streamlined. But we need some more clarity
about the one true tagging app, menu app, etc.</p>
<p>Russell: Flask does the apps thing well, by having a registry of packages and
blesses specific implementations. Everyone should be able to know that pipeline
is better than django-compressor.</p>
<p>Jacob: It doesn’t have to be the core team which does this; they’d much rather
support a community effort.</p>
<p>Alex: It’s not going to happen (talked about it at three panels so far); also
risks stagnation, etc. (Audience member says bollocks, repectfully)</p>
<h3 id="django-2.0">Django 2.0</h3>
<p>Jacob: there will never be a massive change destroying backward compatability
as long as I have anything to do with it; 2.0 will just be 1.9++</p>
<p>Chris: deprecation cycles, etc. are good and breaking stuff is bad.</p>
<h3 id="what-would-you-addremove-from-django">What would you add/remove from Django?</h3>
<p>Russell: probably the stuff around apps/settings/startup. Settings have caused
as many problems as it’s made. App labels (vs just module) are pretty awful.
But still being Django would be difficult.</p>
<p>Alex: the admin; there’s been some reskinning but no real challenges to what
django admin should be.</p>
<p>Jacob: Danny Greenfeld is trying Django Admin 2.</p>
<h3 id="the-django-software-foundation">The Django Software Foundation</h3>
<p>Core committers are all invited to be members, but not all choose to be.</p>
<p>Funding comes from a couple of places:</p>
<ul>
<li><p>Profits from DjangoCon US.</p></li>
<li><p>Membership fees from corporate members.</p></li>
</ul>
<p>It’s been very difficult getting companies to join, in part because it’s a
US-based NFP. It’s also difficult to raise money without having something to
spend it on.</p>
<h3 id="kickstarter-campaigns-etc.">Kickstarter campaigns, etc.</h3>
<p>Alex: This is a good thing. Twisted have created a position to someone to
review patches, etc.</p>
<p>Jacob: The Django community navigates the fraught relationship between OSS and
money better than most. The community is pretty good at coming up with cash
where it’s required to make things happen.</p>
<h3 id="what-will-the-replacement-for-django-be">What will the replacement for Django be?</h3>
<p>Alex: <a href="http://werkzeug.pocoo.org/">werkzeug</a>?</p>
<p>Jacob: Have you watched the <a href="http://meteor.com/">Meteor</a> screencast? The RoR
video in 2004 was a “holy shit” moment because “we have this” (hence open
sourcing Django). This is a “holy shit” moment because we have nothing.</p>
<h3 id="what-should-people-sprint-on">What should people sprint on?</h3>
<p>Russell: 1.6 is coming so people should sprint on triage if they can help;
Porting apps to Python 3; think and talk about the big issues.</p>
<p>Jacob: most of the low-hanging fruit have been picked and everything left is
pretty hard. Pick a specific bug that’s addressing you, or work on a
third-party package.</p>
<h2 id="dylan-jay-on-pyramid-django-and-plone">Dylan Jay on Pyramid, Django and Plone</h2>
<p>There’s a Djangocon tradition of asking people from other Python web frameworks
to speak so we can learn from them. This is that talk. Dylan is a core Plone
contributor and has never written a single line of code for Django; first web
app in 1995 with ISAPI.</p>
<p>Big explosion of web frameworks around 2004 of web frameworks, Rails, Django,
etc. These are all descended from the CGI lineage.</p>
<p>Seperate lineage of Zope then ZTK and Plone. Zope is <em>older</em> than almost
everything in the CGI lineage.</p>
<p>Third lineage of static site generates.</p>
<p>In 1996:</p>
<ul>
<li><p>Webservers serve files at paths.</p></li>
<li><p>CGI = run a script</p></li>
<li><p>OO was big</p></li>
<li><p>CGI was shit, so dude wrote Zope based on objects with traversal and method
invocation based on URL paths.</p></li>
</ul>
<p>ZODB</p>
<p>ZTK:</p>
<ul>
<li><p>Turns out OO isn’t really all that good; use adapters (<code>adaptor :: Interface   i, j =&gt; i -&gt; j</code>)</p></li>
<li><p>Traversal turns into a multiadaptor of Contect, Request and method name to a
browser view.</p></li>
</ul>
<p>Plone:</p>
<ul>
<li>300+ core contributors</li>
<li>400+ plugins (supporting current version)</li>
<li>1000+ commits/month</li>
<li>Sprints, a foundation, etc.</li>
</ul>
<p>Plone services like <a href="https://ploud.com/">ploud</a> and
<a href="http://www.pretagov.com.au">pretagov</a>.</p>
<p>Plone is good at ticking the all boxes you see in government tenders (all by
itself).</p>
<p>The most important thing to consider when evaluating CMS platforms is roles:
reviewers, content editors, site administrators, integrators, frontend
developers, backend developers (in kind of increasing order of technical
ability).</p>
<p>Many of these roles will be present in a large content-oriented site. Being
able to separate and serve the needs of these different user groups.</p>
<p>Frameworks tend to have a straight-line effort/customisation trend, CMS tend to
have non-linear relationship. Once you’ve exceded some limit of customisation,
you’re often better off choosing a framework rather than a CMS.</p>
<p>A framework allows you to start with a pretty blank slate whereas a CMS let’s
you build-up from an already-function-filled starting point.</p>
<p>Pyramid is pretty much the opposite of pyramids:</p>
<ul>
<li>Not ancient</li>
<li>Extensible and flexible (not unchanging for centuries)</li>
<li>Small to big (not big to small)</li>
</ul>
<h2 id="lightning-talks">Lightning Talks</h2>
<h3 id="tim-ansell-talking-about-tims-finance">Tim Ansell talking about Tim’s Finance</h3>
<p><a href="https://github.com/mithro/timsfinance/">Tim’s Finance</a> is an interface to do
various financial things.</p>
<h3 id="jacob-haslehurst-on-permission-migrations">Jacob Haslehurst on Permission Migrations</h3>
<p>Writers, editors, administrators, developers have different permissions.</p>
<p>django-permission-migrations is a small package they’ve pulled out of their
code base. Put permissions in the <code>Meta</code> of the model classes, create a
permissions app for your project and add/remove permissions in the migrations,
define groups in settings, then add migrations which control the permissions.</p>
<h3 id="chris-on-navigation-menus">Chris on Navigation Menus</h3>
<p>Lot’s of Django navigation menus have classes and models and database stuff.
Chris has a simple template tag for doing doing navigation menus. Basically a
helper to write code like:</p>
<pre><code>{% if current == 'apple' %} class=&quot;active&quot; {% endif %}</code></pre>
<p>http://djangosnippets.org/snippets/1729</p>
<h3 id="pandas-loves-ponies">PANDAS loves Ponies</h3>
<p>PANDAS is an R-like stats/data processing package for Python.</p>
<p>pandas-loves-ponies is a library which helps to interface Django with PANDAS
(carry model field names into data frames and similar things).</p>
<h3 id="humphrey-on-form-rendering">Humphrey on form rendering</h3>
<p>Rendering forms isn’t very DRY. Simple app with a template filter to render a
form with a specific tempate.</p>
<p>https://github.com/humphrey/django_formrenderer</p>
<h3 id="danielle-madeley-on-crisper-keeps-crispy-forms-crisper-longer">Danielle Madeley on Crisper keeps Crispy Forms crisper longer</h3>
<p>Currently working on a form heavy app. <a href="http://django-crispy-forms.readthedocs.org/en/latest/">django-crispy-forms</a> is a
django app to make forms a little DRYer. Crisper is an additional - related -
template tag to help detect potential problems with forms, etc. Looks pretty
cool.</p>
<h2 id="thanks">Thanks</h2>
<p>Thanks to all the speakers, sponsors, organisers, volunteers, AV team (the
videos will be at <a href="http://pyvideo.org">pyvideo.org</a> at some point).</p>]]></summary>
</entry>
<entry>
    <title>PyconAU 2012: No, Bad Pony!</title>
    <link href="https://passingcuriosity.com/2012/no-bad-pony/" />
    <id>https://passingcuriosity.com/2012/no-bad-pony/</id>
    <published>2012-08-19T00:00:00Z</published>
    <updated>2012-08-19T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>What turns an idea into a bad pony?</p>
<ul>
<li><p>Is just wrong, impractical, doesn’t fit design.</p></li>
<li><p>Take project in wrong direction</p></li>
<li><p>Doesn’t come with an offer of assistance.</p></li>
</ul>
<p>Ideas that are wrong:</p>
<ul>
<li><p>violates a standard of best practice</p></li>
<li><p>can’t be implemented</p></li>
<li><p>Rusty Russell Interface Level too high</p></li>
<li><p>Idea violates DRY.</p></li>
</ul>
<p>Impractical ideas:</p>
<ul>
<li><p>Not obviously wrong, but they aren’t right either.</p></li>
<li><p>Solving a problem that doesn’t exist. E.g: DB cache doesn’t use the ORM.</p></li>
<li><p>Changes the design contract. (e.g: <code>syncdb</code> doesn’t touch existing tables,
even though it <em>could</em> add manytomany, but doesn’t)</p></li>
<li><p>Address smaller parts of a larger problem.</p></li>
<li><p>Architecture astronauting. Practicality counts; perfectionists with
deadlines, etc.</p></li>
</ul>
<p>Design:</p>
<ul>
<li><p>All the pieces that are part of Django have the same flavour, built by the
same team, we like them.</p></li>
<li><p>Replacing the template engine, the ORM, the test framework, etc. is not
going to happen: we’re happy with and want what we have.</p></li>
<li><p>“I love Django but it’d be great if it was completely different.” is never
going to be compelling.</p></li>
<li><p>The small learning curve (Forms and Models look very similar) is one of the
good things about Django.</p></li>
</ul>
<p>Ignores philosophy</p>
<ul>
<li><p>“Add GROUP BY, HAVING to ORM” misses the point that the ORM is not SQL, by
default.</p></li>
<li><p>Adding AJAX to Forms; Django is a server-side framework.</p></li>
</ul>
<p>Just add a settings</p>
<ul>
<li><p>“A setting is a decision deferred”</p></li>
<li><p>Simplicity is a virtue, just adding settings to core makes Django more
complex and harder to learn.</p></li>
</ul>
<p>Wrong direction</p>
<ul>
<li><p>Feature creep. Django is not a web-server or a database or anything else; it
won’t add features for these things, just use one of them.</p></li>
<li><p>Add a backend. None of these things need to be in core. Adding it to core
really means: “please look after this thing for me”. This is why there are
backend APIs.</p></li>
<li><p>The core doesn’t need to do everything, the community can do awesome stuff,
just because it’s in core doesn’t mean it’s good.</p></li>
<li><p>Adding apps to <code>django.contrib</code>: what does we get from pulling them in?
Nothing, except a slower development schedule. If anything we’re pulling
things <em>out</em> of contrib.</p></li>
<li><p>What is <code>django.contrib</code>? “An collection of optional, defacto standard
implementations of common patterns.” These are pretty much universal.
Tagging, etc.: not so much (and which one).</p></li>
</ul>
<p>Non technical</p>
<ul>
<li><p>Here’s a big job (but I’d like someone else to do it please)</p></li>
<li><p>Process suggestions. If you want news round ups, more blog posts, etc., then
pitch in!</p></li>
<li><p>Massive features: schema evolution, support for non-SQL data stores,</p></li>
</ul>
<p>How do you get your pony?</p>
<ul>
<li><p>NO Putting your name on the ticket CC or saying “me to”.</p></li>
<li><p>NO Posting hyperbole on your blog because it doesn’t have X.</p></li>
<li><p>NO Playing games in the ticket tracker.</p></li>
<li><p>Offer to help</p></li>
<li><p>Or actually help out! Don’t just write code, advocate for your code (why
else will someone review).</p></li>
</ul>]]></summary>
</entry>
<entry>
    <title>Providing default settings for Django applications</title>
    <link href="https://passingcuriosity.com/2010/default-settings-for-django-applications/" />
    <id>https://passingcuriosity.com/2010/default-settings-for-django-applications/</id>
    <published>2010-05-11T00:00:00Z</published>
    <updated>2010-05-11T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>The problem is a simple one: you’re writing a Django application that needs a
setting or two. You know what they’ll be in the vast majority of cases but you
want to make them configurable, just in case. As you’re a good developer you
live by the maxim: Don’t Repeat Yourself so you’d like to define each of these
values and, for ease of documentation, all of them in one place. Alas, you’re
out of luck: Django does not provide any support for applications to supply
their own default values for settings. Thankfully though, all it takes is a
few lines of code and your application can shoehorn its own default values
into the global settings system.</p>
<p>First, a proviso to what follows: I am almost certain that this is a bad idea
and that you should do it. At the very least, you should make sure that your
setting names don’t clash (I like to prefix them with the app name).</p>
<p>The goal is simple: your app should contain a <code>settings</code> module which defines
the default values for your application’s settings. These values should be
injected into Django’s settings system so that <code>manage.py diffsettings</code> and
similar functionality all work as you’d expect.</p>
<p>The approach is just as simple: add some code to the top-level module of your
application that loops over the values in your <code>app.settings</code> module and
inject them into the <code>django.conf.global_settings</code> module and (because it’s
already been initialised by the time apps are loaded) the
<code>django.conf.settings</code> object (being careful not to stop on actual configured
with your default values).</p>
<p>The code itself is pretty simple. From <code>app/__init__.py</code>:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> inject_app_defaults(application):</span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>	<span class="co">&quot;&quot;&quot;Inject an application's default settings&quot;&quot;&quot;</span></span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>	<span class="cf">try</span>:</span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a>		<span class="bu">__import__</span>(<span class="st">'</span><span class="sc">%s</span><span class="st">.settings'</span> <span class="op">%</span> application)</span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a>		<span class="im">import</span> sys</span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>		</span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>		<span class="co"># Import our defaults, project defaults, and project settings</span></span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>		_app_settings <span class="op">=</span> sys.modules[<span class="st">'</span><span class="sc">%s</span><span class="st">.settings'</span> <span class="op">%</span> application]</span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a>		_def_settings <span class="op">=</span> sys.modules[<span class="st">'django.conf.global_settings'</span>]</span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a>		_settings <span class="op">=</span> sys.modules[<span class="st">'django.conf'</span>].settings</span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a>		<span class="co"># Add the values from the application.settings module</span></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a>		<span class="cf">for</span> _k <span class="kw">in</span> <span class="bu">dir</span>(_app_settings):</span>
<span id="cb1-14"><a href="#cb1-14" aria-hidden="true" tabindex="-1"></a>			<span class="cf">if</span> _k.isupper():</span>
<span id="cb1-15"><a href="#cb1-15" aria-hidden="true" tabindex="-1"></a>				<span class="co"># Add the value to the default settings module</span></span>
<span id="cb1-16"><a href="#cb1-16" aria-hidden="true" tabindex="-1"></a>				<span class="bu">setattr</span>(_def_settings, _k, <span class="bu">getattr</span>(_app_settings, _k))</span>
<span id="cb1-17"><a href="#cb1-17" aria-hidden="true" tabindex="-1"></a>				</span>
<span id="cb1-18"><a href="#cb1-18" aria-hidden="true" tabindex="-1"></a>				<span class="co"># Add the value to the settings, if not already present</span></span>
<span id="cb1-19"><a href="#cb1-19" aria-hidden="true" tabindex="-1"></a>				<span class="cf">if</span> <span class="kw">not</span> <span class="bu">hasattr</span>(_settings, _k):</span>
<span id="cb1-20"><a href="#cb1-20" aria-hidden="true" tabindex="-1"></a>					<span class="bu">setattr</span>(_settings, _k, <span class="bu">getattr</span>(_app_settings, _k))</span>
<span id="cb1-21"><a href="#cb1-21" aria-hidden="true" tabindex="-1"></a>	<span class="cf">except</span> <span class="pp">ImportError</span>:</span>
<span id="cb1-22"><a href="#cb1-22" aria-hidden="true" tabindex="-1"></a>		<span class="co"># Silently skip failing settings modules</span></span>
<span id="cb1-23"><a href="#cb1-23" aria-hidden="true" tabindex="-1"></a>		<span class="cf">pass</span></span>
<span id="cb1-24"><a href="#cb1-24" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-25"><a href="#cb1-25" aria-hidden="true" tabindex="-1"></a>inject_app_defaults(<span class="va">__name__</span>)</span></code></pre></div>
<p>You can see the code in a proof of concept application in my
<a href="http://github.com/thsutton/django-application-settings/">django-application-settings</a> project on GitHub.</p>]]></summary>
</entry>
<entry>
    <title>Adding a distance function to MySQL</title>
    <link href="https://passingcuriosity.com/2009/adding-a-distance-function-to-mysql/" />
    <id>https://passingcuriosity.com/2009/adding-a-distance-function-to-mysql/</id>
    <published>2009-08-05T00:00:00Z</published>
    <updated>2009-08-05T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve been working on a project which involves a little bit of geographical
information lately (using <a href="http://djangoproject.com/">Django</a>, if that’s
important to you) and one of the problems I’ve encountered is MySQL’s
incomplete implementation of the various functions that you’d expect of a
geographically-capable database system. One particular lack is a function to
calculate the distance between two points (or, even, other geometric forms).
Thankfully, it’s possible to define it yourself (though convincing
<a href="http://geodjango.org/">GeoDjango</a> to run it is another matter). There are
copies floating around in the ’tubes, but <a href="http://forge.mysql.com/tools/tool.php?id=41">the one I found at MySQL
forge</a> (and also <a href="http://pabloj.blogspot.com/2006/01/distance-function-for-mysql.html">on the author’s
blog</a>) is
a bit broken.</p>
<p>Below, I’ll mention <em>why</em> I think it’s broken and the small change required to
“fix” it.</p>
<p>Alas, it doesn’t work very well on current versions of MySQL (and judging by a
comment on the page, it didn’t work meaningfully back in 2006): it defines a
new function <code>distance</code> from two <code>POINT</code>s to a <code>DOUBLE</code>. For some bizarre
reason, though, it <code>round</code>s it’s result to 0 decimal places. This makes it
pretty useless for local <code>POINT</code>s in a coarse metric like degrees (where 1° of
latitude is around 111km) when your <code>POINT</code>s are local: you’ll often get a
whole lots of <code>0</code>s in your results:</p>
<p>Thankfully, it’s easy to fix: just remove the call to <code>round</code> (or, I suppose,
give it an accuracy rather than let it default to 0 places).</p>
<p>To <a href="http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html">create the
function</a> simply
run the following command somehow – I prefer the <code>mysql</code> command-line, others
[phpMyAdmin][], and still more will put it in an XML file to be interpreted by
a rule engine which is called as part of a semi-automated deployment process
(these are the people that enjoy using Java):</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode sql"><code class="sourceCode sql"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="co">-- Switch delimiter so the ; will work in the function body</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>DELIMITER $$</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="co">-- Create the function</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="kw">CREATE</span> <span class="kw">FUNCTION</span> `distance`(a POINT, b POINT) RETURNS <span class="dt">double</span> </span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>    DETERMINISTIC </span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>    <span class="kw">COMMENT</span> <span class="st">'Calculate the distance between two points'</span> </span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>    <span class="cf">BEGIN</span> </span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a>        <span class="kw">RETURN</span> glength(linestringfromwkb(linestring(asbinary(a), asbinary(b)))); </span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a>    END$$</span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb1-12"><a href="#cb1-12" aria-hidden="true" tabindex="-1"></a><span class="co">-- Switch the delimiter back to ;</span></span>
<span id="cb1-13"><a href="#cb1-13" aria-hidden="true" tabindex="-1"></a>DELIMITER ;</span></code></pre></div>
<p>You’ll notice that this is calling both <code>asbinary</code> (to convert WKB values into
internal MySQL values) and then <code>linestringfromwkb</code> (to convert WKB into
internal MySQL values). Exactly <em>why</em> <code>linestring</code> takes MySQL values and
returns a WKB value, I’m not sure, but it does. If you need to support WKT
inputs, then you’ll wind up calling conversion functions four or five times
per query.</p>
<p>Convincing Django to call this new function is another matter all together.
After a day and a half of trying to understand the GeoDjango back-ends, I gave
up (see <a href="http://groups.google.com/group/geodjango/browse_thread/thread/8f3e66b03c126a32">this thread on the GeoDjango mailing
list</a>
for a little more information) and just used the <code>extra()</code> method to add a
call to the function as a new column and <code>order by</code> it:</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>pc <span class="op">=</span> Postcode.objects.get(postcode<span class="op">=</span><span class="st">'0200'</span>)</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>sel <span class="op">=</span> SortedDict([(<span class="st">'distance'</span>, <span class="st">'distance(location, geomfromtext(</span><span class="sc">%s</span><span class="st">))'</span>)])</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>sel_p <span class="op">=</span> (pc.location.wkt,)</span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a>locations <span class="op">=</span> Locations.objects.extra(select<span class="op">=</span>sel, select_params<span class="op">=</span>sel_p, </span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>    order_by<span class="op">=</span>[<span class="st">'distance'</span>])</span></code></pre></div>]]></summary>
</entry>
<entry>
    <title>Writing view decorators for Django</title>
    <link href="https://passingcuriosity.com/2009/writing-view-decorators-for-django/" />
    <id>https://passingcuriosity.com/2009/writing-view-decorators-for-django/</id>
    <published>2009-07-20T00:00:00Z</published>
    <updated>2009-07-20T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>Using decorators to wrap and modify Django views is quick, easy, composable,
and just about the most awesome thing I’ve seen in a while. It also takes a
little bit of figuring out. Here’s my explanation…</p>
<h2 id="more-than-just-decoration">More than just decoration</h2>
<p>Using a decorator looks (in Python) like this:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a><span class="at">@a_decorator</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> a_function(an_arg):</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>    <span class="cf">return</span> <span class="st">&quot;Functionate: </span><span class="sc">%s</span><span class="st">!&quot;</span> <span class="op">%</span> (an_arg)</span></code></pre></div>
<p>Where <code>a_decorator</code> is some function or other which takes an argument
(<code>a_function</code>, in this particular case) and returns a value. When Python loads
a module containing this code it creates a new function <code>a_function</code> as
normal, but then it calls <code>a_decorator</code> on it and binds the value it returns
to the name <code>a_function</code> rather than the original function created from the
definition. So how do we write these decorators? Just like a normal function!</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> a_decorator(the_func):</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>    <span class="co">&quot;&quot;&quot;</span></span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a><span class="co">    Make another a function more beautiful.</span></span>
<span id="cb2-4"><a href="#cb2-4" aria-hidden="true" tabindex="-1"></a><span class="co">    &quot;&quot;&quot;</span></span>
<span id="cb2-5"><a href="#cb2-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">def</span> _decorated(<span class="op">*</span>args, <span class="op">**</span>kwargs):</span>
<span id="cb2-6"><a href="#cb2-6" aria-hidden="true" tabindex="-1"></a>        <span class="cf">return</span> the_func(<span class="op">*</span>args, <span class="op">**</span>kwargs)</span>
<span id="cb2-7"><a href="#cb2-7" aria-hidden="true" tabindex="-1"></a>    <span class="cf">return</span> _decorated</span></code></pre></div>
<p>But what about parameterised decorators? It’s just a little more involved.
Recall that you use a decorator like this: <code>@the_decorator</code>. It turns out that
such decorator statements don’t just <em>name</em> a decorator to be called, but can
also call a function to return a decorator to be called:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> wrap_in_a(tag):</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>    <span class="co">&quot;&quot;&quot;</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a><span class="co">    Wrap the result of a function in a `tag` HTML tag.</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a><span class="co">    &quot;&quot;&quot;</span></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>    <span class="kw">def</span> _dec(func):</span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a>        <span class="kw">def</span> _new_func(<span class="op">*</span>args, <span class="op">**</span>kwargs):</span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a>            <span class="cf">return</span> <span class="st">&quot;&lt;</span><span class="sc">%s</span><span class="st">&gt;</span><span class="sc">%s</span><span class="st">&lt;/</span><span class="sc">%s</span><span class="st">&gt;&quot;</span> <span class="op">%</span> (tag, func(<span class="op">*</span>args, <span class="op">**</span>kwargs), tag)</span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a>        <span class="cf">return</span> _new_func</span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a>    <span class="cf">return</span> _dec</span>
<span id="cb3-10"><a href="#cb3-10" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-11"><a href="#cb3-11" aria-hidden="true" tabindex="-1"></a><span class="at">@wrap_in_a</span>(<span class="st">'div'</span>)</span>
<span id="cb3-12"><a href="#cb3-12" aria-hidden="true" tabindex="-1"></a><span class="at">@login_required</span></span>
<span id="cb3-13"><a href="#cb3-13" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> my_name(request):</span>
<span id="cb3-14"><a href="#cb3-14" aria-hidden="true" tabindex="-1"></a>    <span class="cf">return</span> request.user.first_name</span></code></pre></div>
<p>The first decorator statement <code>@wrap_in_a('div')</code> calls <code>wrap_in_a('div')</code>
which returns a function (<code>_dec</code>). This function is then applied to the
following definition (<code>@login_required</code> applied to <code>my_name</code>). Simple!</p>
<p>It’s probably a good idea to add a few more bits and pieces to the function
returned by a decorator (copying <code>__doc__</code> and <code>__dict__</code>, for instance), but
that’s the core of it.</p>
<h2 id="using-it-in-django">Using it in Django</h2>
<p>So this is all pretty cool, but how do we use it in Django? We’ll here’s a
<code>anonymous_required</code> decorator that you can use to redirect authenticated
users to their home page if they try to login again:</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb4-1"><a href="#cb4-1" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> anonymous_required(function<span class="op">=</span><span class="va">None</span>, home_url<span class="op">=</span><span class="va">None</span>, redirect_field_name<span class="op">=</span><span class="va">None</span>):</span>
<span id="cb4-2"><a href="#cb4-2" aria-hidden="true" tabindex="-1"></a>    <span class="co">&quot;&quot;&quot;Check that the user is NOT logged in.</span></span>
<span id="cb4-3"><a href="#cb4-3" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-4"><a href="#cb4-4" aria-hidden="true" tabindex="-1"></a><span class="co">    This decorator ensures that the view functions it is called on can be </span></span>
<span id="cb4-5"><a href="#cb4-5" aria-hidden="true" tabindex="-1"></a><span class="co">    accessed only by anonymous users. When an authenticated user accesses</span></span>
<span id="cb4-6"><a href="#cb4-6" aria-hidden="true" tabindex="-1"></a><span class="co">    such a protected view, they are redirected to the address specified in </span></span>
<span id="cb4-7"><a href="#cb4-7" aria-hidden="true" tabindex="-1"></a><span class="co">    the field named in `next_field` or, lacking such a value, the URL in </span></span>
<span id="cb4-8"><a href="#cb4-8" aria-hidden="true" tabindex="-1"></a><span class="co">    `home_url`, or the `USER_HOME_URL` setting.</span></span>
<span id="cb4-9"><a href="#cb4-9" aria-hidden="true" tabindex="-1"></a><span class="co">    &quot;&quot;&quot;</span></span>
<span id="cb4-10"><a href="#cb4-10" aria-hidden="true" tabindex="-1"></a>    <span class="cf">if</span> home_url <span class="kw">is</span> <span class="va">None</span>:</span>
<span id="cb4-11"><a href="#cb4-11" aria-hidden="true" tabindex="-1"></a>        home_url <span class="op">=</span> settings.USER_HOME_URL</span>
<span id="cb4-12"><a href="#cb4-12" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-13"><a href="#cb4-13" aria-hidden="true" tabindex="-1"></a>    <span class="kw">def</span> _dec(view_func):</span>
<span id="cb4-14"><a href="#cb4-14" aria-hidden="true" tabindex="-1"></a>        <span class="kw">def</span> _view(request, <span class="op">*</span>args, <span class="op">**</span>kwargs):</span>
<span id="cb4-15"><a href="#cb4-15" aria-hidden="true" tabindex="-1"></a>            <span class="cf">if</span> request.user.is_authenticated():</span>
<span id="cb4-16"><a href="#cb4-16" aria-hidden="true" tabindex="-1"></a>                url <span class="op">=</span> <span class="va">None</span></span>
<span id="cb4-17"><a href="#cb4-17" aria-hidden="true" tabindex="-1"></a>                <span class="cf">if</span> redirect_field_name <span class="kw">and</span> redirect_field_name <span class="kw">in</span> request.REQUEST:</span>
<span id="cb4-18"><a href="#cb4-18" aria-hidden="true" tabindex="-1"></a>                    url <span class="op">=</span> request.REQUEST[redirect_field_name]</span>
<span id="cb4-19"><a href="#cb4-19" aria-hidden="true" tabindex="-1"></a>                <span class="cf">if</span> <span class="kw">not</span> url:</span>
<span id="cb4-20"><a href="#cb4-20" aria-hidden="true" tabindex="-1"></a>                    url <span class="op">=</span> home_url</span>
<span id="cb4-21"><a href="#cb4-21" aria-hidden="true" tabindex="-1"></a>                <span class="cf">if</span> <span class="kw">not</span> url:</span>
<span id="cb4-22"><a href="#cb4-22" aria-hidden="true" tabindex="-1"></a>                    url <span class="op">=</span> <span class="st">&quot;/&quot;</span></span>
<span id="cb4-23"><a href="#cb4-23" aria-hidden="true" tabindex="-1"></a>                <span class="cf">return</span> HttpResponseRedirect(url)</span>
<span id="cb4-24"><a href="#cb4-24" aria-hidden="true" tabindex="-1"></a>            <span class="cf">else</span>:</span>
<span id="cb4-25"><a href="#cb4-25" aria-hidden="true" tabindex="-1"></a>                <span class="cf">return</span> view_func(request, <span class="op">*</span>args, <span class="op">**</span>kwargs)</span>
<span id="cb4-26"><a href="#cb4-26" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-27"><a href="#cb4-27" aria-hidden="true" tabindex="-1"></a>        _view.<span class="va">__name__</span> <span class="op">=</span> view_func.<span class="va">__name__</span></span>
<span id="cb4-28"><a href="#cb4-28" aria-hidden="true" tabindex="-1"></a>        _view.__dict__ <span class="op">=</span> view_func.__dict__</span>
<span id="cb4-29"><a href="#cb4-29" aria-hidden="true" tabindex="-1"></a>        _view.__doc__ <span class="op">=</span> view_func.__doc__</span>
<span id="cb4-30"><a href="#cb4-30" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-31"><a href="#cb4-31" aria-hidden="true" tabindex="-1"></a>        <span class="cf">return</span> _view</span>
<span id="cb4-32"><a href="#cb4-32" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb4-33"><a href="#cb4-33" aria-hidden="true" tabindex="-1"></a>    <span class="cf">if</span> function <span class="kw">is</span> <span class="va">None</span>:</span>
<span id="cb4-34"><a href="#cb4-34" aria-hidden="true" tabindex="-1"></a>        <span class="cf">return</span> _dec</span>
<span id="cb4-35"><a href="#cb4-35" aria-hidden="true" tabindex="-1"></a>    <span class="cf">else</span>:</span>
<span id="cb4-36"><a href="#cb4-36" aria-hidden="true" tabindex="-1"></a>        <span class="cf">return</span> _dec(function)</span></code></pre></div>
<p>It’s probably not very Django-ish, but you get the impression. Just use it
like Django’s built-in <code>login_required</code> decorator:</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb5-1"><a href="#cb5-1" aria-hidden="true" tabindex="-1"></a><span class="at">@anonynous_required</span></span>
<span id="cb5-2"><a href="#cb5-2" aria-hidden="true" tabindex="-1"></a><span class="kw">def</span> a_view(request):</span>
<span id="cb5-3"><a href="#cb5-3" aria-hidden="true" tabindex="-1"></a>    <span class="cf">return</span> HttpResponse(<span class="st">&quot;We are anonymous! We are legion!&quot;</span>)</span></code></pre></div>
<p>Comments and suggestions welcome!</p>
<p><strong>Update:</strong> Amended the example decorator above to work correctly as
<code>@anonymous_required</code>, <code>@anonymous_required(...)</code> or <code>foo = anonymous_required(foo)</code>.</p>]]></summary>
</entry>
<entry>
    <title>Django form fields and templates</title>
    <link href="https://passingcuriosity.com/2009/django-form-fields-and-templates/" />
    <id>https://passingcuriosity.com/2009/django-form-fields-and-templates/</id>
    <published>2009-06-22T00:00:00Z</published>
    <updated>2009-06-22T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>I’ve been working with <a href="http://djangoproject.org/">Django</a> for the last little while (or long
while) and something that stumped me for a while was a useful, generic
approach to marking-up forms in HTML. In particular, making it possible to use
CSS to style classes of fields (all checkboxes, for instance, or all
date-pickers) effectively. Doing so requires being able to write a selector to
pick such elements out, but I found it very difficult to do so.</p>
<p>The only way, as far as I (and <a href="http://groups.google.com/group/django-users/browse_thread/thread/16493dd43303efd3">the replies on django-users@</a>), is to write a template filter to extract a such a value for you. Thankfully, this it pretty easy:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>    <span class="at">@register.filter</span></span>
<span id="cb1-2"><a href="#cb1-2" aria-hidden="true" tabindex="-1"></a>    <span class="kw">def</span> field_type(field):</span>
<span id="cb1-3"><a href="#cb1-3" aria-hidden="true" tabindex="-1"></a>        <span class="co">&quot;&quot;&quot;</span></span>
<span id="cb1-4"><a href="#cb1-4" aria-hidden="true" tabindex="-1"></a><span class="co">        Get the name of the field class.</span></span>
<span id="cb1-5"><a href="#cb1-5" aria-hidden="true" tabindex="-1"></a><span class="co">        &quot;&quot;&quot;</span></span>
<span id="cb1-6"><a href="#cb1-6" aria-hidden="true" tabindex="-1"></a>        <span class="cf">if</span> <span class="bu">hasattr</span>(field, <span class="st">'field'</span>):</span>
<span id="cb1-7"><a href="#cb1-7" aria-hidden="true" tabindex="-1"></a>            field <span class="op">=</span> field.field</span>
<span id="cb1-8"><a href="#cb1-8" aria-hidden="true" tabindex="-1"></a>        s <span class="op">=</span> <span class="bu">str</span>(<span class="bu">type</span>(field.widget).<span class="va">__name__</span>)</span>
<span id="cb1-9"><a href="#cb1-9" aria-hidden="true" tabindex="-1"></a>        s <span class="op">=</span> s.rpartition(<span class="st">'Input'</span>)[<span class="dv">0</span>]</span>
<span id="cb1-10"><a href="#cb1-10" aria-hidden="true" tabindex="-1"></a>        s <span class="op">=</span> s.lower()</span>
<span id="cb1-11"><a href="#cb1-11" aria-hidden="true" tabindex="-1"></a>        <span class="cf">return</span> s</span></code></pre></div>
<p>I can use the above filter to add a class to my form markup:</p>
<pre class="django"><code>            &lt;div class=&quot;form-field form-{{ field|field_type }}&quot;&gt;
                {{ field.label_tag}}
                {{ field.errors }}
                {{ field }}
            &lt;/div&gt;</code></pre>
<p>Which I can then use in my CSS to style particular widgets without having to do them one-by-one using ID’s:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode css"><code class="sourceCode css"><span id="cb3-1"><a href="#cb3-1" aria-hidden="true" tabindex="-1"></a><span class="fu">.form-field</span> label {</span>
<span id="cb3-2"><a href="#cb3-2" aria-hidden="true" tabindex="-1"></a>    <span class="kw">display</span><span class="ch">:</span> <span class="dv">block</span><span class="op">;</span></span>
<span id="cb3-3"><a href="#cb3-3" aria-hidden="true" tabindex="-1"></a>    <span class="kw">width</span><span class="ch">:</span> <span class="dv">15</span><span class="dt">%</span><span class="op">;</span></span>
<span id="cb3-4"><a href="#cb3-4" aria-hidden="true" tabindex="-1"></a>    <span class="kw">float</span><span class="ch">:</span> <span class="dv">left</span><span class="op">;</span></span>
<span id="cb3-5"><a href="#cb3-5" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb3-6"><a href="#cb3-6" aria-hidden="true" tabindex="-1"></a></span>
<span id="cb3-7"><a href="#cb3-7" aria-hidden="true" tabindex="-1"></a>div<span class="fu">.form-checkbox</span> label {</span>
<span id="cb3-8"><a href="#cb3-8" aria-hidden="true" tabindex="-1"></a>    <span class="kw">width</span><span class="ch">:</span> <span class="dv">85</span><span class="dt">%</span><span class="op">;</span></span>
<span id="cb3-9"><a href="#cb3-9" aria-hidden="true" tabindex="-1"></a>    <span class="kw">float</span><span class="ch">:</span> <span class="dv">right</span><span class="op">;</span></span>
<span id="cb3-10"><a href="#cb3-10" aria-hidden="true" tabindex="-1"></a>    <span class="kw">clear</span><span class="ch">:</span> <span class="dv">right</span><span class="op">;</span></span>
<span id="cb3-11"><a href="#cb3-11" aria-hidden="true" tabindex="-1"></a>}</span>
<span id="cb3-12"><a href="#cb3-12" aria-hidden="true" tabindex="-1"></a>div<span class="fu">.form-checkbox</span> input {</span>
<span id="cb3-13"><a href="#cb3-13" aria-hidden="true" tabindex="-1"></a>    <span class="kw">float</span><span class="ch">:</span> <span class="dv">left</span><span class="op">;</span></span>
<span id="cb3-14"><a href="#cb3-14" aria-hidden="true" tabindex="-1"></a>    <span class="kw">margin-left</span><span class="ch">:</span> <span class="dv">12</span><span class="dt">%</span><span class="op">;</span></span>
<span id="cb3-15"><a href="#cb3-15" aria-hidden="true" tabindex="-1"></a>}</span></code></pre></div>]]></summary>
</entry>
<entry>
    <title>Specifying a UNIX socket using MySQL with Django</title>
    <link href="https://passingcuriosity.com/2009/specifying-a-unix-socket-using-mysql-with-django/" />
    <id>https://passingcuriosity.com/2009/specifying-a-unix-socket-using-mysql-with-django/</id>
    <published>2009-04-16T00:00:00Z</published>
    <updated>2009-04-16T00:00:00Z</updated>
    <summary type="html"><![CDATA[<p>It is sometimes necessary to specify a particular UNIX socket for
<a href="http://mysql.com/">MySQL</a> <a href="http://mysql-python.sourceforge.net/">client libraries</a> to use (for example, when you have
more than one MySQL server on the machine and wish to use one other than the
default). The canonical way to specify a particular UNIX socket for
<a href="http://www.djangoproject.com/">Django</a> is to give the full path as the <code>DATABASE_HOST</code> option in the
project settings file<a href="#fn1" class="footnote-ref" id="fnref1" role="doc-noteref"><sup>1</sup></a>:</p>
<div class="sourceCode" id="cb1"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb1-1"><a href="#cb1-1" aria-hidden="true" tabindex="-1"></a>DATABASE_HOST <span class="op">=</span> <span class="st">'/tmp/mysql.dev.sock'</span></span></code></pre></div>
<p>This works properly and reliably for Django itself but, on my system at least,
it also breaks the <code>manage.py dbshell</code> command: rather than starting and
connecting to the correct database, the <code>mysql</code> errors out with the message</p>
<blockquote>
<p>ERROR 2005 (HY000): Unknown MySQL server host ‘/tmp/mysql.dev.sock’ (1)</p>
</blockquote>
<p>The reason for this should be fairly obvious: <code>/tmp/mysql.dev.sock</code> is not, in
fact, a host name. In fact, this whole solution seems pretty wacky to me (why
put a value that is distinctly <em>not</em> a host name in the “hostname” value?).
The correct way to specify a UNIX socket for the MySQL client libraries to
connect to is using the <code>DATABASE_OPTIONS</code> ([most of] the options can be seen
in the <a href="http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.connections.Connection-class.html#__init__">MySQLdb API documentation</a>):</p>
<div class="sourceCode" id="cb2"><pre class="sourceCode python"><code class="sourceCode python"><span id="cb2-1"><a href="#cb2-1" aria-hidden="true" tabindex="-1"></a>DATABASE_OPTIONS <span class="op">=</span> {</span>
<span id="cb2-2"><a href="#cb2-2" aria-hidden="true" tabindex="-1"></a>    <span class="st">'unix_socket'</span> : <span class="st">'/tmp/mysql.dev.sock'</span>,</span>
<span id="cb2-3"><a href="#cb2-3" aria-hidden="true" tabindex="-1"></a>}</span></code></pre></div>
<p>Doing so ensures that Django is able to connect (using a UNIX socket on the
local host) <em>and</em> that the <code>mysql</code> shell is able to connect (also using a UNIX
socket on the local host). Everything works, everyone is happy, and all of our
options have values that actually make sense. Hoorah!</p>
<section id="footnotes" class="footnotes footnotes-end-of-document" role="doc-endnotes">
<hr />
<ol>
<li id="fn1"><p>See, for example, the <a href="http://docs.djangoproject.com/en/dev/ref/settings/#database-host">documentation for
DATABASE_HOST</a><a href="#fnref1" class="footnote-back" role="doc-backlink">↩︎</a></p></li>
</ol>
</section>]]></summary>
</entry>

</feed>
