RelatedFieldWidgetWrapper

The RelatedFieldWidgetWrapper (found in django.contrib.admin.widgets) is used in the Admin pages to include the capability on a Foreign Key control to add a new related record. (In English: puts the little green plus sign to the right of the control.) In a new application of the FilteredSelectMultiple widget I discussed recently, I needed to add this functionality.

This wrapper is a little complicated, but it didn’t take too much Google searching to find an example.  A Google Code file from something called Crimson Online helped me understand the concept.

The wrapper takes three required parameters plus one optional:

  1. The widget to be wrapped. In my case the FilteredSelectMultiple widget
  2. A relation that defines the two models involved
  3. A reference to the admin site
  4. The Boolean can_add_related (optional)

For the first parameter, I used the widget with its parameters:

FilteredSelectMultiple(('entities'),False,)

The relation confused me at first, but the example made it easy.  The model linked to the form, in this case Item, provides it.

Item._meta.get_field('entities').rel

The third parameter, the admin site object, is used along with the relation to determine if the user has permission to add this related model.  The example used django.contrib.admin.site, which I found doesn’t work.  Instead, I captured the admin_site value from the ModelAdmin class in my admin.py and set it as a variable for the form.  Then I referenced that variable in the \__init__ method of the form to include it in the widget.  This means that the widget has to be assigned within the __init__ method of the form.

self.admin_site

The fourth parameter can be used to override the permission check performed by the widget.  However, when a user without the permission to add clicks that little green plus sign, an ugly 500 error is returned.

Here is the code used:

in admin.py:

class ItemAdmin(admin.ModelAdmin):
    form = ItemAdminForm

    def __init__(self, model, admin_site):
        super(ItemAdmin,self).__init__(model,admin_site)
        self.form.admin_site = admin_site # capture the admin_site

admin.site.register(Item, ItemAdmin)

in forms.py

from django.contrib.admin.widgets import FilteredSelectMultiple, RelatedFieldWidgetWrapper

class ItemAdminForm(forms.ModelForm):
    entities = forms.ModelMultipleChoiceField(queryset=None,label=('Select Entities'),)

    def __init__(self, *args, **kwargs):
        super(ItemAdminForm,self).__init__(*args, **kwargs)
        # set the widget with wrapper
        self.fields['entities'].widget = RelatedFieldWidgetWrapper(
                                                FilteredSelectMultiple(('entities'),False,),
                                                Item._meta.get_field('entities').rel,
                                                self.admin_site)
        self.fields['entities'].queryset = Entity.objects.all()

    class Media:
        ## media for the FilteredSelectMultiple widget
        css = {
            'all':('/media/css/widgets.css',),
        }
        # jsi18n is required by the widget
        js = ('/admin/jsi18n/',)

    class Meta:
        model = Item

UPDATE:

I’ve published a follow up post that covers using this wrapper outside of the admin application. See More RelatedFieldWidgetWrapper – My Very Own Popup.

 

Using the FilterSelectMultiple Widget

I will soon be starting a new project at work, and one of the mockups calls for a side by side control to select multiple choices in a many-to-many relationships.  The default control used by Django is the SelectMultiple widget.

 

However, this can get unwieldy when the number of choices grows.  Instead, I wish to use a filter select, as seen in the Django admin when assigning permissions to a user or group.

 

It didn’t take too much research to find a Django snippet as an example.  http://djangosnippets.org/snippets/2466/.  I pretty much copied his example, except for the CSS file called ‘uid -manage-form.css’.  This must be part of his application, because I couldn’t find any other reference to it online.

Here is the form code I ended up with:

from django.contrib.admin.widgets import FilteredSelectMultiple

class BookForm(ModelForm):
    authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all(),
                                          label=('Select Authors'),
                                          widget=FilteredSelectMultiple(
                                                    ('authors'),
                                                    False,
                                                 ))
    class Media:
        css = {
            'all':('/media/css/widgets.css',),
        }
        # jsi18n is required by the widget
        js = ('/admin/jsi18n/',)

    class Meta:
        model = Book

As the example shows, I included the tag for the form media in the <head> section of the template, which inserts the CSS and JS calls.

<head>
    ...
    {{ bookform.media }}
</head>

Once my designer gets a hold of this, I’m sure it will look great.

UPDATE: For an example of using the RelatedFieldWidgetWrapper to include the capability to add a new record, see this post.

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.

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.