Django System Configuration via Admin Interface

We wanted to allow system administrators to easily configure a number of parameters through the web interface itself. We also wanted to do this without too much additional coding, or installing any more dependencies. So we hacked together the following solution using a standard django model that's part of your app, which can be edited through the standard interface. It's not entirely elegant, but it works. Step 1 - Create configuration model
Each setting has it's own field. This makes it easy to edit everything on the one screen. The downside is that adding new settings will require adding new columns to the db table using a migration script, or manual db manipulation. The __unicode__ method defines what shows up in the admin interface when users click on the corresponding model.
#################################
class SystemConfiguration(models.Model):
    some_setting = models.IntegerField('Some Setting', help_text="What does it do.")
    some_setting2 = models.IntegerField('Some Setting2', help_text="What does it do.")

    def __unicode__(self):
        return 'Click to Edit System Configurations.'
################################

Step 2 - Configure admin interface access
We add this to the admin interface as normal, but specify special permissions to ensure users can not add more than one configuration record, and likewike can not delete the last configuration record. We only ever want one in the system (unless you want to have different configurations which you could hot-swap using a boolean flag, or different configurations for different environments, but for simplicity, one record is enough)
#################################
class SystemConfigurationAdmin(admin.ModelAdmin):

    def has_add_permission(self, request):
        c = SystemConfiguration.objects.count()
        return False if c > 0 else True

    def has_delete_permission(self, request, obj=None):
        c = SystemConfiguration.objects.count()
        return True if c > 1 else False
admin.site.register(SystemConfiguration, SystemConfigurationAdmin)
################################

Step 3 - Accessing your settings
To access your settings just import the SystemConfiguration model and call: SystemConfiguration.objects.get().some_setting Because there's only 1 record, you don't need to pass anything to the get method. This keeps things simple. If you wanted multiple configuration profiles, you could just get by a specific string, e.g. SystemConfiguration.objects.get(env='prod').some_setting

Comments

Popular posts from this blog

Wkhtmltopdf font and sizing issues

Import Google Contacts to Nokia PC Suite

Can't delete last blank page from Word