Django Templates for the Designer

There’s no need to know Python or Django to work well with Django templates. A good understanding of the way HTML is generated will take the designer most of the way.

A common shortcut in rendering a form in the template is to use {{ form.as_p }}.  This will include all of the included fields from the form, along with labels and errors.   A nice side effect is that changes to the fields – whether adding a new field, taking one away, or changing its format – are reflected immediately when the app is restarted without any modifications necessary for the template itself.  Here’s an example:

<form action="." method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" /></form>

However, without an understanding of the underlying form, and possibly a related model, it can be difficult for the non-developer to predict which fields will be included. When using a basic Form, one just needs to check the form definition to see the list of fields.  This form is a good example:

class UserSelectForm(Form):
    user = ChoiceField(required=True)
    reg_date = DateField(required=False)

Just the two fields listed will be included in the generated HTML.

With a ModelForm, things get a little more complicated. Before viewing an example, let’s start with a quick set of rules:

  1. All fields from the related model will be included
  2. UNLESS, the field is marked as editable=False in the model definition
  3. The fields attribute in the ModelForm‘s Meta section can be used to limit the form to a subset of the fields
  4. The exclude attribue, also in the Meta section, is used to omit fields from the form
  5. Additional fields specified in the form that are not part of the model will also be included

For more information, see Creating Forms from Models in the Django documentation.

Here’s an example:

class TrainingScheduleForm(ModelForm):
    class_date = DateFieldMultiFormat(required=True)
    class_time = TimeFieldMultiFormat(required=True)
    send_email = fields.BooleanField(required=False)

    class Meta:
        model = TrainingSchedule
        exclude = ('training_class',)

The model attribute tells us to look at the TrainingSchedule model and include those fields that are editable.

class TrainingSchedule(ModelBase):
    training_class = models.ForeignKey(TrainingClass,null=False,blank=False)
    class_date = models.DateField(null=False,blank=False)
    class_time = models.TimeField(null=False,blank=False)
    location = models.CharField(max_length=255,null=True,blank=True)
    campus = models.CharField(max_length=255,null=True,blank=True)
    capacity = models.IntegerField(blank=True,null=True)
    display_flag = models.BooleanField(default=True)

Then, we look at the exclude attribute to see that the training_class field is not included. Class_date and class_time are explicitly listed only because of a need to override the default field type, but the send_email is an extra field that is not part of the model. It is included as well. So, the final list of fields in the template is:

  • class_date
  • class_time
  • location
  • campus
  • capacity
  • display_flag
  • send_email

Using the {{ form.as_p }} shortcut, the HTML will include this snippet:

<p><label for="id_class_date">Class date</label><input type="text" name="class_date" id="id_class_date" /> </p>
<p><label for="id_class_time">Class time</label><input type="text" name="class_time" id="id_class_time" /> </p>
<p><label for="id_location">Location</label><input id="id_location" type="text" name="location" maxlength="255" /> </p>
<p><label for="id_campus">Campus</label><input id="id_campus" type="text" name="campus" maxlength="255" /> </p>
<p><label for="id_capacity">Capacity</label><input type="text" name="capacity" id="id_capacity" /> </p>
<p><label for="id_display_flag">Display flag</label><input checked="checked" type="checkbox" name="display_flag" id="id_display_flag" /> </p>
<p><label for="id_send_email">Send email:</label> <input type="checkbox" name="send_email" id="id_send_email" /></p>

Note that both the labels and fields have IDs just waiting to be styled. If there were any errors generated, those sections would also be included, with all of the ID and class goodness.

Shortcomings

Sometimes, the designer wants to change the order of the fields, put the errors in a different spot, assign other classes and IDs, and insert additional information in the template. In these cases, one can skip the shortcut, and specify the form pieces individually. Here is an example of a template with individual fields listed:

<form action="." method="post"> {% csrf_token %}

<div id="signup_details">

{{ form.non_field_errors }}

<p>{{ form.training_class.errors }}{{ form.training_class.label_tag }} {{ form.training_class }}</p>
<p>{{ form.training_schedule.errors }}{{ form.training_schedule.label_tag }} {{ form.training_schedule }}</p>

<fieldset id="new_schedule">
<legend>Create New Schedule</legend>
<p>{{ form.class_date.errors }}{{ form.class_date.label_tag }} {{ form.class_date }}</p>
<p>{{ form.class_time.errors }}{{ form.class_time.label_tag }} {{ form.class_time }}</p>
<p>{{ form.location.errors }}{{ form.location.label_tag }} {{ form.location }}</p>
<p>{{ form.campus.errors }}{{ form.campus.label_tag }} {{ form.campus }}</p>
</fieldset>

</div>
<div id="signup_flags">
<p>{{ form.send_email.errors }}{{ form.send_email.label_tag }} {{ form.send_email }}</p>
<p>{{ form.attended.errors }}{{ form.attended.label_tag }} {{ form.attended }}</p>
<p>{{ form.exempt.errors }}{{ form.exempt.label_tag }} {{ form.exempt }}</p>
</div>

<br clear="left" /><br />

<input type="submit" value="Save" />
<INPUT TYPE="BUTTON" VALUE="Cancel" onClick="history.go(-1)">
</form>

Note a couple of things. The tag {{ form.non_field_errors }} is where any form level errors would be displayed. Likewise, the {{ form.field_name.errors }} tag holds the place for individual field errors.

Once the tags are in the form, the designer can move them around and add additional HTML – notice the use of fieldset above.

See more information on the individual tags in Working With Forms.

Hope this helps a few designers figure out Django templates.  Please leave any comments or questions below.

A Better Way – Don’t!

In an earlier post, I talked about using form.save(commit=False) in a class based view, and I showed a way to do it.  However, I wasn’t looking far enough back to see the real question:

How can I add information not found on the form to the object before saving?

Thanks to a reply way down in this Google Groups post, I found what I needed, and I kicked my self for not seeing this earlier. Since I was using the default form logic to save the object, I could send the additional value to the form.

    ## Include the instance object before saving
    def form_valid(self, form):
        form.instance.institution = self.institution
        return super(EventCreateView,self).form_valid(form)

I like this solution better than what I provided in the earlier post because it is a better object oriented approach.

Of course, I have used the older example all over my applications, so I’ve got some refactoring to do.

Installing Oracle Client on Ubuntu 11.10

Oracle Logo(Another post written for personal documentation)

Get Software

Download these three packages from Oracle for the proper operating system (32 bit for me):

  • Instant Client Basic-Lite
  • Instant Client SDK
  • Instand Client SQLPlus

Unzip and copy to /opt/oracle/11_2/instantclient

Set LD_LIBRARY_PATH

Create /etc/ld.so.conf.d/oracle_instantclient.conf:

#Oracle client LD_LIBRARY_PATH setting
/opt/oracle/11_2/instantclient

Update cache:

sudo ldconfig -v

Symbolic Link to Library

ln -s libclntsh.so.10.1 libclntsh.so

Set ORACLE_HOME

export ORACLE_HOME=/opt/oracle/11_2/instantclient

Install Python Library

The library is called cx-oracle. Use your favorite installation method. (Don’t forget about your virtual environment!)

That’s It

Hope I remembered everything.

UPDATE

Found another post that outlines the procedure maybe a little better than I did, and includes notes on setting up tnsnames.ora. See Install Oracle Instant Client 11.1 and cx_Oracle 4.4 on Ubuntu 8.04 on Technoblog.

Using form.save(commit=False) in a Class Based View

UPDATE: I found a better way to do this.  See this post.

In this example, I once again hadn’t used a generic view for this create function, since I needed to add a value that is not in the form to the new object before the save.

    if form.is_valid():
        new_rec = form.save(commit=False)
        new_rec.institution = institution
        new_rec.save()
        return HttpResponseRedirect(reverse('cat_list'))

The value for institution comes from the user’s session area. The above is the accepted pattern to add the data to the object.

So how can we do this in a class based view?

An override of form_valid() in the class will handle this case.

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.institution = self.kwargs['institution']
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

(Putting the institution value in kwargs is the subject for another post. One could also use an object variable.)

UPDATE: I found a better way to do this.  See this post.

The reader who just wants to know how to do this can stop here. However….

Is this the best way to do this?

I’m not very skilled in the art of overriding methods, so I am a little concerned about the forward compatibility of this solution.
Let’s first see the upstream definitions of this method.
The method is defined in ModelFormMixin as follows:

    def form_valid(self, form):
        self.object = form.save()
        return super(ModelFormMixin, self).form_valid(form)

And above that we find a simpler method in FormMixin:

    def form_valid(self, form):
        return HttpResponseRedirect(self.get_success_url())

I like how the ModelFormMixin method is able to refer back to the original using the super function, but I don’t know how I can jump over the immediate ancestor to call back the original method. Is this possible? Does it matter?

I am slightly concerned that changes to the method in FormMixin that may come along in future versions may be overlooked with this solution. Sure, I have to check these things during an upgrade anyway, but I would like to perform this as “correctly” as possible.

Please leave your suggestions, thoughts and comments below.

UPDATE: I found a better way to do this.  See this post.

Class Based Views: CreateView Example

For this example I’m not starting with a generic view. That’s because the code includes support for an extra submit button – in this case “Save and Add Another”. Without it, I would have used the generic view.

Before:


@permission_required('calendars.add_eventtype')
def create_type(request):
    evttypeform = EventTypeForm(request.POST or None)

    if evttypeform.is_valid():
        evttypeform.save()
        if '_addanother' in request.POST:
            return HttpResponseRedirect(reverse('create_type'))

        return HttpResponseRedirect(reverse('list_type'))

    return render_to_response('eventtype_form.html',
                              {'form' : evttypeform, 'create_form': True,
                    'calendar_menu': CalendarName.menu.all(),   },
                               context_instance=RequestContext(request))

Perhaps the Generic View would have looked something like this (not tested):

@permission_required('calendars.add_eventtype')
def create_type(request):
    return create_object(request,
                         form_class = EventTypeForm,
                         post_save_redirect=reverse('list_type'),
                         template_name='eventtype_form.html',
                         extra_context={'create_form': True,
                                        'calendar_menu': CalendarName.menu.all(),})    

After:

class TypeCreateView(CreateView):
    template_name = 'eventtype_form.html'
    model = EventType
    form_class = EventTypeForm

    def get_success_url(self):
        if '_addanother' in self.request.POST:
            return reverse('create_type')
        return reverse('list_type')

    ## Override dispatch to apply the permission decorator
    @method_decorator(permission_required('calendars.add_eventtype'))
    def dispatch(self, request, *args, **kwargs):
        return super(TypeCreateView, self).dispatch(request, *args, **kwargs)

    ## Additional context
    def get_context_data(self, **kwargs):
        context = super(TypeCreateView, self).get_context_data(**kwargs)
        context['calendar_menu'] = CalendarName.menu.all()
        context['create_form'] = True
        return context 

One of the benefits of the class based views is to be able to override individual methods. Here the get_success_url method can handle the extra functionality of the “Add Another” button.

Class Based Views – UpdateView Example

Yet another simple example. I basically just took the DeleteView example and changed a couple of things.

Before:

@permission_required('calendars.change_eventtype')
def update_type(request,id):
    return update_object(request,
                         model=EventType,
                         object_id=id,
                         template_name='eventtype_form.html',
                         post_save_redirect=reverse('list_type'),
                       extra_context = {'calendar_menu': CalendarName.menu.all()})

After:

class TypeUpdateView(UpdateView):
    template_name = 'eventtype_form.html'
    model = EventType

    def get_success_url(self):
        return reverse('list_type')

    ## Override dispatch to apply the permission decorator
    @method_decorator(permission_required('calendars.change_eventtype'))
    def dispatch(self, request, *args, **kwargs):
        return super(TypeUpdateView, self).dispatch(request, *args, **kwargs)

    ## Additional context
    def get_context_data(self, **kwargs):
        context = super(TypeUpdateView, self).get_context_data(**kwargs)
        context['calendar_menu'] = CalendarName.menu.all()
        return context 

With another example, the generic view declared a form_class instead of a model. The model declaration is not necessary since the related model is tied to the form in its meta section. However, in the class based generic view, both were required (or a queryset could have also been used). I guess the related model info doesn’t make its way back to the class. Hmmmm.

Class Based Views – DeleteView Example

Another simple one – this time a DeleteView from delete_object.

Before:

@permission_required('b2c.delete_b2ctrack')
def delete_track(request,id):
    track = get_object_or_404(B2CTrack, pk=id)
    if track.allow_delete:
        return delete_object(request,
                             model=B2CTrack,
                             object_id=id,
                             post_delete_redirect=reverse('track_list'),
                             template_name='track_confirm_delete.html')
    else:
        return HttpResponseRedirect(reverse('track_view', kwargs = {'pk':id} ))

After:

class TrackDeleteView(DeleteView):
    template_name = 'track_confirm_delete.html'
    model = B2CTrack

    def get_success_url(self):
        return reverse('track_list')

    ## Override dispatch to apply the permission decorator
    @method_decorator(permission_required('b2c.delete_b2ctrack'))
    def dispatch(self, request, *args, **kwargs):
        return super(TrackDeleteView, self).dispatch(request, *args, **kwargs)

    ## Only return object if the allow_delete property is True
    def get_object(self, *args, **kwargs):
        object = super(TrackDeleteView,self).get_object(*args, **kwargs)
        if object.allow_delete:
            return object
        else:
            raise Http404

The old code would redirect back to the view for the same object if the allow_delete property was false. (allow_delete is a property I use on my models to check for dependent DB entries) Since one has to monkey with the URL to even attempt a delete of an object that isn’t allowed, I decided a 404 was more appropriate. Lesson for the User: Don’t Monkey with URLs!!

Class Based Views – DetailView Example

This is a simple example that shows how to convert the object_detail generic view to the class based DetailView.

Before:

@permission_required('b2c.view_b2ctrack')
def view_track(request,id):
    return object_detail(request,
                         queryset=B2CTrack.objects.all(),
                         object_id=id,
                         template_name='track_detail.html')

After:

class TrackDetailView(DetailView):
    template_name = 'track_detail.html'
    model = B2CTrack

    ## Override dispatch to apply the permission decorator
    @method_decorator(permission_required('b2c.view_b2ctrack'))
    def dispatch(self, *args, **kwargs):
        return super(TrackDetailView, self).dispatch(*args, **kwargs)  

Only odd thing I encountered was that the new View wants to see the ID of the object named ‘pk’, instead of ‘id’ that I was using. The DEV branch of Django includes the pk_url_kwarg variable that allows a rename, but it isn’t available in v1.3.

Note that I could have used queryset instead of model to specify the data source. Either will give the same result in this example.

More on Class Based Views – Redirect If Data Missing

In this view, rather than raising a 404 if a piece of data is missing, I redirect back to a page where the user can specify the value.

def list_session(request):
    event_id = request.session.get('event_id',None)
    try:
        event = Event.objects.get(pk=event_id)
    except:  #No event - back to staff page to select
        return HttpResponseRedirect(reverse('staff'))

    queryset = B2CSession.objects.filter(event = event)

    params = {'queryset': queryset,
              'paginate_by': DEFAULT_PAGINATION,
              'template_name': 'session_list.html',
              'extra_context': {'event': event,
                                'session': session}}
    return object_list(request, **params)

I wanted to implement this same functionality using a class based view, so I looked into the available methods to override. The dispatch method was really the only choice. My solution:

def dispatch(self, request, *args, **kwargs):
        ## If there is no event_id set in the session, return to staff page for a chance to select one
        try:
            self.event = Event.objects.get(pk=request.session.get('event_id',None))
        except Event.DoesNotExist:
            return HttpResponseRedirect(reverse('staff'))
        ## Normal processing
        return super(ListSessionView, self).dispatch(request, *args, **kwargs)  

What do you think? Is this the best way to make this work? Leave your comments below.

My Eclipse Setup for Django

Eclipse LogoDocumenting my Eclipse setup as I install onto a fresh Ubuntu 11.04 machine.

First, is the choice of Eclipse package. There are several that will work for Python/Django – basically any of the Language IDE focused bundles. This time I am using the Java EE setup (v3.7.1), but I have also installed the standard Java and C/C++ builds with success.

I wish that there was an install procedure for Eclipse that would setup the menus, etc. The package available in the Ubuntu Software Center is usually an older version (currently 3.5) and is a basic install only. It is up to the user to add the additional features desired. Instead, I download the package, extract to /opt, and setup the menus myself.

Next is Aptana Studio 3. This includes PyDev (which supplies Python and Django functionality), web tools, Ruby support, and other goodies. For Python/Django support only, I have used the standalone PyDev install instead. However, once PyDev is installed, the Aptana install complains if installed later.

Also important is version control support. Eclipse comes with CVS included, and clients for other systems are available. Since I use Subversion, I install the Subclipse add-in from Tigrs. Check the version numbers of both your Eclipse and svn installs to select the correct Subclipse package. Eclipse will complain about JavaHL not being available the first time SVN is used. There is a setting in Eclipse (under Team/SVN) to switch to the SVNKit client.

I have also used Eclipse SQL Explorer for database access. It is a bit of a fight to get the proper drivers and configuration all figured out, but worth it to have DB commands within the Eclipse environment here. Read more about SQL Explorer in this earlier post.

That is pretty much it. I may at a later date talk about setting up virtual environments in Eclipse, so stay tuned.

Any questions or suggestions? Please post a comment below.