Skip to main content

Posts

Showing posts from April, 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 obj.save() This is documented in the Django Docs , but I found it particularly useful.

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

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. core/utils.py 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 fo