Tuesday, April 26, 2011

Django Admin Override Save for Model

Sometimes it's nice to be able to add custom code to the save method of objects in the Django Admin.  So, when editing an object on the Admin object detail page (change form), adding the following method override to your ModelAdmin in admin.py will allow you to add custom code to the save function.

In admin.py:  
class MyModelAdmin(admin.ModelAdmin):

    def save_model(self, request, obj, form, change):
        # custom stuff here

This is documented in the Django Docs, but I found it particularly useful.

Wednesday, April 13, 2011

Django Pattern for Reporting Errors/Messages in Views Part 2: Managers

In my last post, I discussed how you can use a simple UserMessage class in your views to report simple error messages.   This way, you can keep track of errors and report them to the users in a clean fashion.

One thing I didn't expand upon much is how to create some manager methods to cleanly lookup model instances and report any errors to the UserMessage class.  I think this approach is a little nicer than catching exceptions all over the place, because you don't have to clutter your views with try/catch blocks.

In the example below, we create a custom manager that looks up a model instance of "MyModel" with the given hash.  If the selected instance of "MyModel" does not exist or if some other error occurs, it writes an error message to "message" instance passed into it.  You can customize this as you see fit.  For example, in the code below, I pass in a "user" instance that can be used to check permissions in this method. 

class MyModelManager(models.Manager):
    # In this case, we pass in a user, a unique hash for a 
    # "MyModel" object instance, and an optional message. 
    def get_mymodel(self, user, mymodel_hash, message=None):
        mymodel = []
        # If the message previously set an error, return immediately  
        if message:
            return None, message
            # if the user is an admin, search all MyModels for the matching hash 
            if user.is_staff:
                mymodel = MyModel.objects.get(hash=mymodel_hash, enabled=True)
            # if the user is NOT an admin, search user-related MyModels for the matching hash 
                mymodel = user.mymodel_set.get(hash=mymodel_hash, enabled=True)
        except MyModel.DoesNotExist:
            message = UserMessage()
            message.title = _("Not found")
            message.text = _("MyModel does not exist")
        return mymodel, message

Saturday, April 2, 2011

Django Pattern for Reporting Errors/Messages in Views

I've tried tried to find a decent way to design my Django views so that I can smoothly report errors to users.  The errors that I am concerned about are errors that users encounter if they are preforming actions that are typically NOT normally encountered through normal use of the user interface.  For example, if users try to directly access a URL of an object that doesn't exist, if they post incorrect values to a URL, or a required value doesn't exist in the user's session.

In a utility module, I create a message class that I to store message information.  While view processing is taking place, if an error takes place, this class will be used to store the error title, text, and "back" url link.

class UserMessage():
    def __init__(self, title="", text=[], url=None):
        self.title = title
        self.text = text if hasattr(text, '__iter__') else [text]
        self.url = url 

The view continually checks for the existance of a UserMessage instance.  (In the example below, "message" variable is an instance of UserMessage)  If an error condition occurs, part of the handing will be to create a new UserMessage, and the view renders an error page using the template defined by message_template_name and the variables set in the UserMessage instance.

def  detail_view(request, myobject_slug, template_name="", 
    context = {}
    message = None
    if not message: 
        # call custom manager method; pass in message for error handling
        myobject, message = MyObject.objects.get_myobject(myobject_slug, message)
    if not message:
        if not myobject.is_authroized(...):   # do come check here 
            message = utils.UserMessage("Permission Denied",  
                     "You are not authorized to view this.") 
    if not message:
        if myobject.is_wrong_type(...):   # do some check here
            message = utils.UserMessage("Invalid Type",   
                    "This is the wrong type")
            message.url = reverse('index')
    if not message:
        # normal view stuff here  
        form = forms.MyForm(....)
        if request.method == "POST":
            form = forms.MyForm(data=request.POST, ....)
            if form.is_valid():
                # do other stuff here as needed
                return HttpResponseRedirect(reverse('success_page'))
    return render_to_response(template_name, context,

Create a message template to display the errors.

{% extends "base.html" %}

{% block title %}{{ block.super }}{{ message.title }}{% endblock title %} 

{% block content %} 
  <div>{{ message.title }}</div>
  {% for text in message.text %}
  <div>{{ text }}</div>
  {% endfor %}
  <div><a href="{{ message.url }}">Back</a></div>
{% endblock content %} 

With some modifications, this method can be used with ajax requests.  Note that I do not recommend using the system for catching Django form errors.  Django handles that nicely as it is.

There are probably better approaches for this sort of thing, but this approach seems to work for me in many cases.  Hope it's useful.  Comments welcome.