Skip to main content

Posts

Django Models Mixins

One thing I've been experimenting with is model Mixins.  For example, the aim is to create small abstract classes that are each focused around a particular function.  These abstract classes can then be added to arbitrary models to apply those functions to models as desired. For example, say I define a RatingsFields abstract class and a TrackingFields abstract class.  These abstract classes can be mixed into any other model that we wish to add rating or tracking functionality to. core/mixins.py from djangoratings.fields import RatingField # 3rd party module class RatingFields(models.Model): rating = RatingField( range =5) # 5 possible rating values, 1-5 class Meta: abstract = True class TrackingFields(models.Model): deleted_on = models.DateTimeField(blank= True , null= True ) created = models.DateTimeField(auto_now_add= True ) modified = models.DateTimeField(auto_now= True ) class Meta: abstract = True...

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...

Django Pattern For Model Permissions

I think I've found an interesting way to set up a permissions system in Django.  This system allows you to specify granular permissions on specific object instances and is template friendly. Setup The Permissions Infrastructure First, you create an "abstract" Permissions class that models will use as a permissions base class.  This base permissions class sets up simple caching for the permissions and creates some common methods to be used by all permissions objects.  The current_user represents the logged in that you want to check permissions for a particular object. Notice the use of threadlocals here.  If current_user is not supplied in the constructor, the class will try to lookup the current_user from a variable by the threadlocals middleware (see below).  Be warned, however, some people don't seem to like the threadlocals approach .  To be honest, I'm still trying to evaluate the pluses and minuses, but it sure makes certain things in the templat...

Django Environment Quick Setup

aptitude install python-virtualenv   # for debian-based systems virtualenv --no-site-packages myproject cd myproject/ source ./bin/activate pip install django  south  django-extensions pip install flup  psycopg2 mkdir -p ./etc/ ./var/log/ ./app/django/ cd ./app/django/ django-admin.py startproject mymain

Django Project Setup Conveniences

Whenever I start a new Django project, there are several common steps that I to help standardize my setups. In settings.py ... I define a PROJECT_ROOT variable which contains the path to the project directory.  This is useful for various settings in the setup.py: import sys, os PROJECT_ROOT = os.path.dirname(__file__) I set my MEDIA_ROOT to be a path relative to the PROJECT_ROOT.   Of course, I will need to create this directory on the filesystem.  MEDIA_ROOT = os.path.join(PROJECT_ROOT, '..','htdocs','media').replace('\\','/') + '/' And I set a relative TEMPLATE_DIRS path.  I will need to make this directory as well. TEMPLATE_DIRS = (     os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'), ) Sometimes I add extra directories to the path so I can store specific packages within the project directory. (I might use this if I want to keep all related modules together). sys.path...