Skip to main content

Posts

Showing posts from 2011

Django: Using Caching to Track Online Users

Recently I wanted a simple solution to track whether a user is online on a given Django site.  The definition of "online" on a site is kind of ambiguous, so I'll define that a user is considered to be online if they have made any request to the site in the last five minutes. I found that one approach is to use Django's caching framework to track when a user last accessed the site.  For example, upon each request, I can have a middleware set the current time as a cache value associated with a given user.  This allows us to store some basic information about logged-in user's online state without having to hit the database on each request and easily retrieve it by accessing the cache. My approach below.  Comments welcome. In settings.py: # add the middleware that you are about to create to settings MIDDLEWARE_CLASSES = ( .... 'middleware.activeuser_middleware.ActiveUserMiddleware' , .... ) # Setup caching per Django docs. In actuality, you

Django Permission TemplateTag

In a previous post , I wrote about a way to keep track of user permissions on a model instance.  For example, I suggested that each model have a permissions subclass that could be instantiated with a user instance passed as a constructor argument.  Methods on that permissions class could then be called to determine if that user has permission to perform various actions. I also suggested that the threadlocals module could then be used to pass in the user instance to the permissions object in the Django template.  However, from various readings, I get the impression that threadlocals may not be the best thing for passing arguments in a template function.   Therefore, I decided to use a more traditional route of creating a template tag to do something similar. I created a template tag that lets you surround a block of HTML code to hide or show the contents based on the return value of the permission function.  The tag below basically says, "if the logged in user has 'can_edit

Django: Logging Quickstart in Django 1.3

Logging is always one of those things that seems like there is a lot of boilerplate code that I tend to always have to lookup oneline each time.  Though logging is very customizable, most of the time I need simply to only need log to a file or files.   Therefore, I'm writing this in hopes of compling a simple configuration that can be dropped into a project.  My understanding is still rudimentary so feel free to drop a comment. A logging framework is built into Django 1.3 which makes it easier to integrate into a given project.  The logging framework contains three main components: formatters, handlers, and loggers.  Formatters determine how the output will be displayed when it is logged.  Handlers handle where output is logged, whether that be a file, the counsole, or an email.  Loggers are associated with handlers and are the objects that one interacts with when logging something.  As in the example below, more than one formatter, handler or logger can be defined in a projec

Django: Executing manage.py from Anywhere

One nice convenience would be to have a way to call manage.py from anywhere within a virtual environment.  For example, if I want to execute 'manage.py shell', it would be nice to be able to execute that from anywhere rather than having to change directory to where manage.py lives. We can already run management commands from anywhere using django-admin by utilizing the --settings flag, but doing this requires a lot of typing. And wrapping the django-admin in a shell script seems inelegant somehow. Instead, I wrote a small python script based off of manage.py.  This can be placed in the ./bin directory in the virtualenv.  The  DjangoManageSettings  object is meant to be customized on a per project basis, and I intend to make it so it can be passed in from a file configuration somewhere. Anyway, thought I would share.  I'm curious to see other approaches to this. # ---------- ${VIRTUAL_ENV}/bin/django_manage.py ------------------------- #!/usr/bin/env python import

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 templates easi

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

Introduction

This blog will document my adventures in Django, the Python web framework.  It is a direct fork of my Linux Info  blog, but will be specifically utilized for documenting my Django activity.  Though my aim is to post Django code and examples that are helpful, there will most certainly be better/different ways to approach various challenges.  Any comments are much appreciated. Joe