<?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>Web-In-Sight &#187; django</title>
	<atom:link href="http://web-in-sight.nl/tag/django/feed/" rel="self" type="application/rss+xml" />
	<link>http://web-in-sight.nl</link>
	<description>Inzicht in internet en werken</description>
	<lastBuildDate>Mon, 30 Jan 2012 09:00:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Django FormWizard best .. well .. useful practices</title>
		<link>http://web-in-sight.nl/2010/02/24/django-formwizard-best-well-useful-practices/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=django-formwizard-best-well-useful-practices</link>
		<comments>http://web-in-sight.nl/2010/02/24/django-formwizard-best-well-useful-practices/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 11:10:56 +0000</pubDate>
		<dc:creator>Gerard</dc:creator>
				<category><![CDATA[All ENGLISH articles]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[wizard]]></category>

		<guid isPermaLink="false">http://www.gerardjp.com/?p=1231</guid>
		<description><![CDATA[Django FormWizard usefulness: emulating decorators .. more to come <a href="http://web-in-sight.nl/2010/02/24/django-formwizard-best-well-useful-practices/">Lees verder <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Edit</em>: After some re-writes of this post it is finally setup in a manor that is clean and failsafe.</p>
<p>After researching and setting up two FormWizards in Django I concluded some things that might be useful to others. Hence this post.</p>
<h2>Having userdata available throughout the wizard</h2>
<p>I&#8217;ve seen some solutions on the net for this but when you handle data from several models over different steps the best way to handle this is using Django&#8217;s session framework. In parse_params() in the beginning and end we repectively get/set data and store our data.</p>
<pre>def parse_params(self, request, *args, **kwargs):
    current_step = self.determine_step(request, *args, **kwargs)
    form = self.get_form(current_step, request.POST)

    # Pickup the dict from the users session or create a new one
    wizdata = request.session.get('wizdata') or {}

    # Your code goes here. E.g. set a value in the dict
    wizdata['some_key'] = 'Some value'

    # Store the possibly changed dict back in the users session.
    request.session['wizdata'] = wizdata
</pre>
<p>So whatever you do with the user data, it&#8217;s safe, and we can access it in any step throughout the wizardry.</p>
<pre>def render_template(self, request, form, previous_fields, step, context=None):
    wizdata = request.session.get('wizdata')

    # Your other code goes here. E.g. a conditional on previously set data.
    if wizdata.get('some_key'):
        # Do something with your data
        wizdata['some_key'] = 'Some other value'

    # And again, simply store the dict in the users session.
    request.session['wizdata'] = wizdata
</pre>
<p>You can imagine that in the parse_params() and the render_template() method you respectively have the &#8216;if current_step == &#8216; or &#8216;if step == &#8216; statements along the way. All having the wizdata dict available.</p>
<p>This also works in the done() method. Simply get the dict one last time from the user session.</p>
<pre>def done(self, request, form_list):
    wizdata = request.session.get('wizdata')

    # Other code here

    # Cleanup
    del request.session['wizdata']
</pre>
<p>Then, for tidyness, at the end of done() we remove the dict from the user session.</p>
<h3>Gotchas</h3>
<p>There can be stale data, in the form of our stored dicts, left behind when wizard sessions are not finished by the user. This also is true for the sessions itself. As stated in the <a title="The Django docs about sessions" href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#clearing-the-session-table" target="_blank">The Django docs about sessions</a> you should clean up the sessions from time to time.</p>
<p>Anybody that has improvements, questions or compliments please drop me a line <img src='http://web-in-sight.nl/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>GrtzG</p>
<div class="AWD_like_button "><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fweb-in-sight.nl%2F2010%2F02%2F24%2Fdjango-formwizard-best-well-useful-practices%2F&amp;send=false&amp;layout=button_count&amp;width=&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font=arial&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:px; height:21px;" allowTransparency="true"></iframe></div>]]></content:encoded>
			<wfw:commentRss>http://web-in-sight.nl/2010/02/24/django-formwizard-best-well-useful-practices/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Django: get distinct field selection</title>
		<link>http://web-in-sight.nl/2009/12/16/django-get-distinct-field-selection/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=django-get-distinct-field-selection</link>
		<comments>http://web-in-sight.nl/2009/12/16/django-get-distinct-field-selection/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 13:11:55 +0000</pubDate>
		<dc:creator>Gerard</dc:creator>
				<category><![CDATA[All ENGLISH articles]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.gerardjp.com/?p=1131</guid>
		<description><![CDATA[A function for Django that is a simple and safe solution to get a distinct (group by) field selection from a model. <a href="http://web-in-sight.nl/2009/12/16/django-get-distinct-field-selection/">Lees verder <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I recently have been dinging around in <a href="http://www.djangoproject.com/" target="_blank">Django</a>&#8216;s <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" target="_blank">ORM</a> because I needed a certain &#8216;fields &#8230; group by&#8217; selection. I was very impressed by the logic that the Django developers put in there. Especially the joins and aggregations that have been released with version 1.1. However, after a hours of testing and googling, I was not able to solve my problem with it. I needed a distinct selection like this:</p>
<pre>SELECT id, name FROM myapp_model WHERE owner_id='1' GROUP BY name;</pre>
<p>This would have been (easily) possible except for the WHERE clause on ownership that screwed me. Since the SQL statement was that simple I decided to write a bypass function that get&#8217;s the data straight from the database. It&#8217;s readonly access and I dont do anything more with it then create a list of links. Even more so, from a <a href="http://en.wikipedia.org/wiki/KISS_principle" target="_blank">KISS</a> point of view this code is easier to read back after several months.</p>
<p>And for reusability I turned it in to a function. It takes the model and the distinct field, and for my purpose the needed ownership as parameter:</p>
<pre>from django.db import connection

def get_latest_objects(model_name=None, distinct_field=None, user_id=None):
    """ Get lastest distinct selection (as tuples) of a given model
    """
    model_name = model_name.lower()
    query = ("select id,%(distinct_field)s from myapp_%(model_name)s "
                "where owner_id='%(user_id)s' "
                "group by %(distinct_field)s;") % {
                    'model_name': model_name,
                    'distinct_field': distinct_field,
                    'user_id': user_id,
                    }
    cursor = connection.cursor()
    cursor.execute(query)</pre>
<p>There&#8217;s not much to it, I just hope it helps you to avoid &#8216;the hard way&#8217;. And it helps to keeps your view methods more readable because you dont need anything more then this:</p>
<pre>latest_objects = get_latest_objects(model_name='MyModel',
                        distinct_field='name',
                        user_id=request.user.id)</pre>
<p>What is returned (latest_objects) is a list of tuples that you can unpack in your templates straight away. Note that there&#8217;s no error checking in there, because I know what I&#8217;m doing <img src='http://web-in-sight.nl/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />  Besides, worst case you get back an empty list and possible errors are caught when you write your tests. You do write those don&#8217;t you?</p>
<p>Grtz Gerard.</p>
<div class="AWD_like_button "><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fweb-in-sight.nl%2F2009%2F12%2F16%2Fdjango-get-distinct-field-selection%2F&amp;send=false&amp;layout=button_count&amp;width=&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font=arial&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:px; height:21px;" allowTransparency="true"></iframe></div>]]></content:encoded>
			<wfw:commentRss>http://web-in-sight.nl/2009/12/16/django-get-distinct-field-selection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Django: QueryScreener, a record level ownership development auditor</title>
		<link>http://web-in-sight.nl/2009/10/26/django-queryscreener-a-record-level-ownership-development-auditor/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=django-queryscreener-a-record-level-ownership-development-auditor</link>
		<comments>http://web-in-sight.nl/2009/10/26/django-queryscreener-a-record-level-ownership-development-auditor/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 16:41:12 +0000</pubDate>
		<dc:creator>Gerard</dc:creator>
				<category><![CDATA[All ENGLISH articles]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.gerardjp.com/?p=1049</guid>
		<description><![CDATA[QueryScreener is a middleware development tool that helps to avoid unwanted data disclosure once you go into production. It monitors queries to the models and warns you when queries are executed that lack a ownership clause.  <a href="http://web-in-sight.nl/2009/10/26/django-queryscreener-a-record-level-ownership-development-auditor/">Lees verder <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>During the development stage of a Django app I&#8217;m working on I was exploring how to best implement rowlevel user ownerships. There are several ways to overwrite methods on <a title="Object Managers" href="http://docs.djangoproject.com/en/dev/topics/db/managers/" target="_blank">object managers</a> and even the Django admin interface is properly configurable to take a ownership from &#8220;request.user&#8221;.</p>
<p>But since wrongfull data disclosure is absolutely unacceptable I was still afraid that I would miss something somewhere. A nice example I ran into was populating a dropdown list in a form, where all records were visible instead of only those owned by the logged in user.</p>
<p>That got me thinking and eventually I wrote this small but sweet piece of <a title="Middleware" href="http://docs.djangoproject.com/en/dev/topics/http/middleware/" target="_blank">middleware</a>. Further elaboration below the code.</p>
<pre class="python" name="code">from django.db import connection
import re

"""
QueryScreener is a middleware development tool. This tool helps to avoid
unwanted data disclosure once you go into production.

It monitors queries to the models in your model_list and warns you when queries
are executed that do not contain a ownership where clause. And thus can be a
potential data disclosure hazard.

It requires a owner attribute in your model definition, e.g:

    owner = models.ForeignKey(User, editable=False)

Edit the 'model_list' below for what models should be monitored. And add
QueryScreener to MIDDLEWARE_CLASSES in you settings.py

Note: This can/should only be used while running Django's testserver command
with e.g: ./manage.py runserver 192.168.1.81:8000
"""

class QueryScreener(object):

    model_list = ['myapp_customer', 'myapp_order', 'myapp_product']

    def process_view(self, request, view_func, view_args, view_kwargs):
        if len(connection.queries) &gt; 0:
            query_parse(connection.queries, self.model_list, 'process_view')

    def process_response(self, request, response):
        if len(connection.queries) &gt; 0:
            query_parse(connection.queries, self.model_list, 'process_response')
        return response

def query_parse(self, model_list, caller_process):

    for query in connection.queries:
        for modelname in model_list:
            modelstring = 'FROM `'+modelname

            if re.search(modelstring, query['sql']) and not \
                re.search(r'^SELECT.\(1\).AS', query['sql']):

                reg = re.compile(r'^SELECT.*WHERE.*owner.*(ORDER BY.*)?$',
                                    re.DOTALL)

                if not reg.search(query['sql']):
                    print ('&lt;&lt;&lt; WARNING &gt;&gt;&gt; Query execution without ownership '
                            'clause, called from "' + caller_process + '"')
                    print query['sql']

            if re.search(r'^SELECT.\(1\).AS.`a`.FROM.*WHERE.*$', query['sql']):
                print ('&lt;&lt;&lt; Django Farted &gt;&gt;&gt;')
#                print query['sql']</pre>
<p><em>Update1: The &#8216;ORDER BY&#8217; in the regex needs to be optional.</em><br />
<em>Update2: Django does a &#8216;try update&#8217; in save_base() without owner (seperated the select statement)<br />
</em></p>
<p>The comment in the code above sums up how to get it working. What it does is print a warning and the query in question that does not respect ownership. If enabled while developing just keep track of your console output for:</p>
<pre>&lt;&lt;&lt; WARNING &gt;&gt;&gt; Query execution without ownership clause, called from "process_response"</pre>
<p>Should you  have suggestion, criticism, or words of admiration then please, do tell me <img src='http://web-in-sight.nl/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>GrtzG</p>
<div class="AWD_like_button "><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fweb-in-sight.nl%2F2009%2F10%2F26%2Fdjango-queryscreener-a-record-level-ownership-development-auditor%2F&amp;send=false&amp;layout=button_count&amp;width=&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font=arial&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:px; height:21px;" allowTransparency="true"></iframe></div>]]></content:encoded>
			<wfw:commentRss>http://web-in-sight.nl/2009/10/26/django-queryscreener-a-record-level-ownership-development-auditor/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>&#8220;Walk-around&#8221; for pre lighttpd-1.4.23 feature &#8220;fix-root-scriptname&#8221;</title>
		<link>http://web-in-sight.nl/2009/08/15/walk-around-for-pre-lighttpd-1-4-23-feature-fix-root-scriptname/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=walk-around-for-pre-lighttpd-1-4-23-feature-fix-root-scriptname</link>
		<comments>http://web-in-sight.nl/2009/08/15/walk-around-for-pre-lighttpd-1-4-23-feature-fix-root-scriptname/#comments</comments>
		<pubDate>Sat, 15 Aug 2009 09:41:24 +0000</pubDate>
		<dc:creator>Gerard</dc:creator>
				<category><![CDATA[All ENGLISH articles]]></category>
		<category><![CDATA[Technical]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.gerardjp.com/?p=923</guid>
		<description><![CDATA[Walk-around should ofcourse be workaround but it feels more like a walk around &#8230; Today I &#8216;moved&#8217; the first version of my application from the Django development setup (run via &#8220;./manage runserver&#8221;) to a lighttpd/fcgi production setup. Been cleaning up &#8230; <a href="http://web-in-sight.nl/2009/08/15/walk-around-for-pre-lighttpd-1-4-23-feature-fix-root-scriptname/">Lees verder <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Walk-around should ofcourse be workaround but it feels more like a walk around &#8230; <img src='http://web-in-sight.nl/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Today I &#8216;moved&#8217; the first version of my application from the Django development setup (run via &#8220;./manage runserver&#8221;) to a lighttpd/fcgi production setup. Been cleaning up code and concluded I wanted the app straight on the &#8216;/&#8217; or docroot with a simple config like this:</p>
<pre>HTTP["host"] == "example.int" {
    fastcgi.server = (
        "/" =&gt; (
            "main" =&gt; (
                "host" =&gt; "192.168.1.2",
                "port" =&gt; 8000,
                "check-local" =&gt; "disable",
                #"fix-root-scriptname" =&gt; "enable",
            )
        ),
    )
}</pre>
<p>After a lot of messing around and not getting the aformetioned setup to work I found <a href="http://redmine.lighttpd.net/issues/show/729" target="_blank">the &#8216;PATH_INFO&#8217; problem</a>. The easiest way is to have <a href="http://www.lighttpd.net/2009/6/19/1-4-23-leaving-the-nest" target="_blank">lighttpd version 1.4.23</a> running, because then you can enable:</p>
<pre>    "fix-root-scriptname" =&gt; "enable",</pre>
<p>And therewith actually acces your app on &#8220;/&#8221; instead of &#8220;/dd&#8221; as shown in the below example under the line with &#8220;fastcgi.server (&#8220;.</p>
<p>The problem however is that lighttpd version 1.4.23 is not apt-get-able yet and I like my systems clean. So here&#8217;s the somewhat cumbersome but functional example that works:</p>
<pre>HTTP["host"] == "example.int" {
    fastcgi.server = (
        "/dd" =&gt; (
            "main" =&gt; (
                "host" =&gt; "192.168.1.2",
                "port" =&gt; 8000,
                "check-local" =&gt; "disable",
            )
        ),
    )

    url.rewrite-once = (
        "^(/.*)$" =&gt; "/dd/$1",
    )
}</pre>
<p>What happens is that lighttpd passes an incoming request like &#8220;/url_to_something&#8221; to your fcgi proces, but fcgi is on &#8220;/dd/url_to_something&#8221;. So with the rewrite rule we make sure the &#8220;/dd&#8221; prefix is added, other wise it would not be passed to the fcgi handler.</p>
<p>The problem however is that you should modify all your in-app links so they would be prefixed with /dd otherwise you end up with a 404. This can be globally resolved by adding the line below to your Django settings.py</p>
<pre>FORCE_SCRIPT_NAME = ""</pre>
<p>Django then strips of the &#8220;/dd&#8221; prefix just before it gets parsed by your django app URL Dispatcher.</p>
<p>So when lighttpd version 1.4.23 is in the debian and/or Ubuntu repository, you apt get it and adjust your setup in 3 places.</p>
<p>Remove the rewrite rule and the &#8220;dd&#8221; part from your lighttpd host config and disable the FORCE_SCRIPT_NAME in your settings.py. Doing it like this keeps everything running with the least adjustments now and only a little work to be done in the near future.</p>
<div class="AWD_like_button "><iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fweb-in-sight.nl%2F2009%2F08%2F15%2Fwalk-around-for-pre-lighttpd-1-4-23-feature-fix-root-scriptname%2F&amp;send=false&amp;layout=button_count&amp;width=&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font=arial&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:px; height:21px;" allowTransparency="true"></iframe></div>]]></content:encoded>
			<wfw:commentRss>http://web-in-sight.nl/2009/08/15/walk-around-for-pre-lighttpd-1-4-23-feature-fix-root-scriptname/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

