<?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>zoia.org &#187; Java</title>
	<atom:link href="http://www.zoia.org/blog/category/programming/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.zoia.org/blog</link>
	<description>Por Roberto Zoia</description>
	<lastBuildDate>Wed, 01 Sep 2010 14:29:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Iterating over items of selection fields in django templates using newforms</title>
		<link>http://www.zoia.org/blog/2007/03/24/iterating-over-items-of-selection-fields-in-django-templates-using-newforms/</link>
		<comments>http://www.zoia.org/blog/2007/03/24/iterating-over-items-of-selection-fields-in-django-templates-using-newforms/#comments</comments>
		<pubDate>Sat, 24 Mar 2007 16:28:33 +0000</pubDate>
		<dc:creator>Roberto</dc:creator>
				<category><![CDATA[CMS]]></category>
		<category><![CDATA[Django]]></category>
		<category><![CDATA[English]]></category>
		<category><![CDATA[Fotografia]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Ubuntu]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://www.zoia.org/blog/2007/03/24/iterating-over-items-of-selection-fields-in-django-templates-using-newforms/</guid>
		<description><![CDATA[A year ago I wrote a custom CheckboxSelectMultiple control for django. My application needed to display a series of checkboxes on the webpage, but the default django control did not allow iteration over each checkbox when the control was rendered in the template (as it was possible with the RadioSelect control). This finer control was [...]]]></description>
			<content:encoded><![CDATA[<p>A year ago I wrote a <a href="http://www.zoia.org/blog/2006/02/22/django-and-custom-checkboxselectmultiplefield/">custom CheckboxSelectMultiple</a> control for <a href="http://www.djangoproject.com">django</a>.  My application needed to display a series of checkboxes on the webpage, but the default django control did not allow iteration over each checkbox when the control was rendered in the template (as it was possible with the RadioSelect control).  This finer control was necessary because I needed to insert extra HTML between each checkbox.</p>

<p>As of version 0.95, django has been under heavy changes, and my custom control no longer works.  In particular, the old forms module is being discarded in favor of the newforms module that will become the default forms module sometime in the future.  A good explanation can be found in the on-site django documentation, under <a href="http://www.djangoproject.com/documentation/newforms/#migration-plan">newforms-migration plan</a>.</p>

<p>The good news is that newforms allows access to individual items of the form fields, multiple-select fields included. The newforms documentation is still work in progress, so it took me a while to figure out how to do it&#8230; by inspecting the source code and regression tests. It seems pretty obvious now, should have asked in the <a href="http://groups.google.com/group/django-users">django-users list</a>.</p>

<p>The example code has been tested with django svn release 4812 (2007-3-23).</p>

<p><strong><span style="text-decoration: underline;">2007-03-27</span></strong>: By mistake I published an incorrect version of <code>views.py</code>.  Code has been corrected so that now   <code>add_post</code> saves the tag field as expected. <span style="text-decoration: line-through;">(<code>Post</code> has a many-to-many relationship with <code>Tag</code>, so <code>form.save()</code> is not enough to save the form data.)</span></p>

<p><strong><span style="text-decoration: underline;">2007-04-12</span></strong>:  The code for <code>views.py</code> has been corrected again.  The code posted 2007-03-27 works, but as I discovered later, there is no need to create another object (<code>p = Post(**cleandata)</code>) to handle the many-to-many field data.  <code>form.save()</code> takes care of everything, as expected.</p>

<p><strong><span style="text-decoration: underline;">2007-04-24</span></strong>:  You may be interested in <a href="http://www.zoia.org/blog/2007/04/23/using-dynamic-choices-with-django-newforms-and-custom-widgets/">this post</a>.</p>

<h2>template</h2>

<p><pre>
</pre><pre class="brush: xml;">&lt;/p&gt;

&lt;ul&gt;
{% for choice in form.base_fields.tag.choices %}
&lt;li&gt; ({{ choice.0 }}, {{ choice.1 }}) &lt;/li&gt;
{% endfor %}
&lt;/ul&gt;

&lt;p&gt;</pre>
</p>

<h2>models.py</h2>

<p><pre>
</pre><pre class="brush: python;">&lt;/p&gt;

&lt;h1&gt;-&lt;em&gt;- coding: utf-8 -&lt;/em&gt;-&lt;/h1&gt;

&lt;h1&gt;models.py&lt;/h1&gt;

&lt;p&gt;from django.db import models&lt;/p&gt;

&lt;p&gt;class Tag(models.Model):
    tag = models.CharField(maxlength=20)&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def __str__(self):
    return self.tag
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;class Post(models.Model):
    # other fields here:
    # text = models.CharField(maxlength=255)
    # title = models.CharField(maxlength=50)
    # etc.
    tag = models.ManyToManyField(Tag)&lt;/p&gt;

&lt;p&gt;</pre>
</p>

<h2>views.py</h2>

<p><pre>
</pre><pre class="brush: python;">&lt;/p&gt;

&lt;h1&gt;-&lt;em&gt;- coding: utf-8 -&lt;/em&gt;-&lt;/h1&gt;

&lt;h1&gt;views.py&lt;/h1&gt;

&lt;p&gt;from django.template import Context, loader
from django.http import HttpResponse, HttpResponseRedirect&lt;/p&gt;

&lt;p&gt;from django import newforms as forms
from django.newforms.widgets import *&lt;/p&gt;

&lt;p&gt;from project.models import *&lt;/p&gt;

&lt;p&gt;def add_post(request):
    postForm = forms.models.form_for_model(Post)
    if request.method == 'POST':
       form = postForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(&quot;/&quot;)
    else:
         form = postForm()
         t = loader.get_template('add_post.html')
         c = Context({
               'form': form,
               })&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;     return HttpResponse(t.render(c))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;</pre>
</p>

<h2><span style="text-decoration: line-through;">views.py</span></h2>

<p>This is an old version of <code>views.py</code>.  The code works, but as I discovered later, there is no need to create another object (<code>p = Post(**cleandata)</code>) to handle the many-to-many field data.  form.save() takes care of everything, as expected.
<pre>
</pre><pre class="brush: python;">&lt;/p&gt;

&lt;h1&gt;-&lt;em&gt;- coding: utf-8 -&lt;/em&gt;-&lt;/h1&gt;

&lt;h1&gt;views.py&lt;/h1&gt;

&lt;p&gt;from django.template import Context, loader
from django.http import HttpResponse, HttpResponseRedirect&lt;/p&gt;

&lt;p&gt;from django import newforms as forms
from django.newforms.widgets import *&lt;/p&gt;

&lt;p&gt;from project.models import *&lt;/p&gt;

&lt;p&gt;def add_post(request):
    postForm = forms.models.form_for_model(Post)
    if request.method == 'POST':
        form = postForm(request.POST)
        if form.is_valid():
           cleandata = form.clean_data
           # use the form tag ids to select the Tag instances
           # related to this Post entry
           tag = Tag.objects.in_bulk(cleandata['tag'])
           # need to delete the tag ids from clean data,
           # otherwise p = Post(** cleandata) will complain that
           # tag is not a parameter of Post( )
           del cleandata['tag']&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;       # create an instance of Post from the form data
       p = Post(**cleandata)
       p.save()   # need to save so p gets an id.
       p.tag = tag
       p.save()

       return HttpResponseRedirect(&amp;amp;amp;quot;/&amp;amp;amp;quot;)
   else:
   form = postForm()

   t = loader.get_template('add_post.html')
   c = Context({
          'form': form,
    })

    return HttpResponse(t.render(c))
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;</pre>
</p>
]]></content:encoded>
			<wfw:commentRss>http://www.zoia.org/blog/2007/03/24/iterating-over-items-of-selection-fields-in-django-templates-using-newforms/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apuntes de programación Java</title>
		<link>http://www.zoia.org/blog/2006/08/12/apuntes-de-programacion-java-2/</link>
		<comments>http://www.zoia.org/blog/2006/08/12/apuntes-de-programacion-java-2/#comments</comments>
		<pubDate>Sat, 12 Aug 2006 15:27:08 +0000</pubDate>
		<dc:creator>Roberto</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.zoia.org/blog/2006/08/12/apuntes-de-programacion-java-2/</guid>
		<description><![CDATA[En esta página he colgado los resúmenes que he ido haciendo para las clases Programación Avanzada del semestre 2006-I de la Facultad de Ingeniería de la Universidad de Piura. Son una primera versión y están escritos en tono algo informal. Introducción Inheritance Exceptions io streams Polymorphism Interfaces Listas Collections Super-repaso de la mitad del curso. [...]]]></description>
			<content:encoded><![CDATA[<p>En esta página he colgado los resúmenes que he ido haciendo para las clases Programación Avanzada del semestre 2006-I de la <a title="Universidad de Piura, Facultad de Ingeniería" target="_blank" href="http://www.ing.udep.edu.pe">Facultad de Ingeniería de la Universidad de Piura</a>.  Son una primera versión y están escritos en tono algo informal.</p>

<ul />

<ol>
    <li><a target="_blank" href="http://zoia.org/files/pav/PAVresumen1.pdf">Introducción</a></li>
    <li><a href="http://zoia.org/files/pav/PAVResumen2.pdf" /><a target="_blank" href="http://zoia.org/files/pav/PAVResumen2.pdf">Inheritance</a></li>
    <li><a href="http://zoia.org/files/pav/PAVresumen3_Excepciones.pdf" /><a target="_blank" href="http://zoia.org/files/pav/PAVresumen3_Excepciones.pdf">Exceptions</a></li>
    <li><a href="http://zoia.org/files/pav/PAVresumen4_io.pdf" /><a href="http://zoia.org/files/pav/PAVresumen4_io.pdf">io streams</a></li>
    <li><a href="http://zoia.org/files/pav/resumen5_polimorfismo.pdf" /><a target="_blank" href="http://www.zoia.org/files/pav/resumen5_polimorfismo.pdf">Polymorphism</a></li>
    <li><a target="_blank" title="Interfaces" href="http://zoia.org/files/pav/resumen6_interfaces.pdf">Interfaces</a></li>
    <li><a title="Listas enlazadas" href="http://zoia.org/files/pav/resumen7_listas.zip">Listas</a></li>
    <li><a title="Colecciones" href="http://zoia.org/files/pav/resumen8_colecciones.zip">Collections</a></li>
</ol>

<p><a title="Superrepaso" href="http://zoia.org/files/pav/PAVrepaso1.pdf">Super-repaso</a> de la mitad del curso.  15 páginas para que los alumnos identifiquen sus dudas&#8230;</p>

<ul />

<p>Comentarios y sugerencias a gmail arroba zoia punto roberto.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.zoia.org/blog/2006/08/12/apuntes-de-programacion-java-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Links:  Java Game Programming</title>
		<link>http://www.zoia.org/blog/2006/06/09/links-java-game-programming/</link>
		<comments>http://www.zoia.org/blog/2006/06/09/links-java-game-programming/#comments</comments>
		<pubDate>Fri, 09 Jun 2006 22:14:22 +0000</pubDate>
		<dc:creator>Roberto</dc:creator>
				<category><![CDATA[Game programming]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.zoia.org/blog/2006/06/09/links-java-game-programming/</guid>
		<description><![CDATA[Se me ocurrió que podía intentar desarrollar un Tetris-clone con los alumnos del curso de Programación Avanzada.  Tetris es un juego que tiene una lógica sencilla, es adictivo, y es relativamente sencillo de implementar (por lo menos, implementar una versión no muy sofisticada). Buscando documentación en Google sobre cómo implementar un doublebuffer mínimo-mínimo en Java, [...]]]></description>
			<content:encoded><![CDATA[<p>Se me ocurrió que podía intentar desarrollar un Tetris-clone con los alumnos del curso de Programación Avanzada.  <a target="_blank" title="Tetris en Wikipedia" href="http://en.wikipedia.org/wiki/Tetris">Tetris</a> es un juego que tiene una lógica sencilla, es adictivo, y es relativamente sencillo de implementar (por lo menos, implementar una versión no muy sofisticada).</p>

<p>Buscando documentación en Google sobre cómo implementar un doublebuffer mínimo-mínimo en Java, encontré <a target="_blank" title="Killer Game programming in Java" href="http://fivedots.coe.psu.ac.th/~ad/jg/">esta página de Andrew Davison:  Killer Game programming in Java</a>.   Tengo un buen número de libros de programación de juegos (la mayoría para C++) y he leído basantes artículos sobre el asunto,  y  esta página web es buena y clara y toca prácticamente todos los temas necesarios para empezar a desarrollar juegos en Java.  Cada tema está en un archivo pdf e incluye el código.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.zoia.org/blog/2006/06/09/links-java-game-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Programming Notes</title>
		<link>http://www.zoia.org/blog/2006/05/28/java-programming-notes/</link>
		<comments>http://www.zoia.org/blog/2006/05/28/java-programming-notes/#comments</comments>
		<pubDate>Mon, 29 May 2006 02:33:16 +0000</pubDate>
		<dc:creator>Roberto</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.zoia.org/blog/2006/05/28/java-programming-notes/</guid>
		<description><![CDATA[Buscando material para las clases de Java encontré esta página de Fred Swartz:  http://www.leepoint.net/notes-java/index.html]]></description>
			<content:encoded><![CDATA[<p>Buscando material para las clases de Java encontré esta página de Fred Swartz:  <a href="http://www.leepoint.net/notes-java/index.html">http://www.leepoint.net/notes-java/index.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.zoia.org/blog/2006/05/28/java-programming-notes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Apuntes de programación Java</title>
		<link>http://www.zoia.org/blog/2006/05/21/apuntes-de-programacion-java/</link>
		<comments>http://www.zoia.org/blog/2006/05/21/apuntes-de-programacion-java/#comments</comments>
		<pubDate>Sun, 21 May 2006 18:00:37 +0000</pubDate>
		<dc:creator>Roberto</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.zoia.org/blog/archives/2006/05/21/apuntes-de-programacion-java/</guid>
		<description><![CDATA[He creado una página donde iré colgando los resúmenes de las clases de Programación Java que estoy dictando este semestre en Facultad de Ingeniería de la Universidad de Piura en Lima:  apuntes-de-programacion-java.]]></description>
			<content:encoded><![CDATA[<p>He creado una página donde iré colgando los resúmenes de las clases de Programación Java que estoy dictando este semestre en <a target="_blank" title="Universidad de Piura, Facultad de Ingeniería" href="http://www.ing.udep.edu.pe">Facultad de Ingeniería de la Universidad de Piura</a> en Lima:  <a href="http://www.zoia.org/blog/apuntes-de-programacion-java">apuntes-de-programacion-java</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.zoia.org/blog/2006/05/21/apuntes-de-programacion-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
