André Caron
André Caron

Reputation: 45224

Additional fields in Django admin interface

Suppose I have some persistent model property that's not backed up by a model field, how do I allow editing this field in the admin interface?

Example setup:

# models.py

# appropriate imports...

class MyModel(Model):
      # regular fields.
    foo = CharField(max_length=50)
    bar = BooleanField()
    # ...

      # custom property, backed by a file.
    def _get_meh ( self ):
        return ... # read from file
    def _set_meh ( self, value ):
        ... # write to file.
    meh = property(_get_meh, _set_meh)

meh's value is actually stored in a file on disk who's path depends on the value in foo. I'd like to be able to edit meh's value from the admin interface.

# admin.py

# appropriate imports...

class MyModelAdmin(ModelAdmin):
    # what do I put here?

Note: in case someone needs to ask, I'm using Django version 1.2.1, but upgrading is possible if that is required by your solution. Anything that runs on Python 2.5 will do, this I can't really upgrade for the moment.

Upvotes: 0

Views: 3088

Answers (2)

tinsukE
tinsukE

Reputation: 940

Take a look at this: http://www.scribd.com/doc/68396387/Adding-extra-fields-to-a-model-form-in-Django%E2%80%99s-admin-%E2%80%93-Hindsight-Labs (this one went offline, http://www.hindsightlabs.com/blog/2010/02/11/adding-extra-fields-to-a-model-form-in-djangos-admin/)

Basically, you'll create a MyModelFrom subclassed from forms.ModelForm and:

  1. Add the extra meh fields to the MyModelFrom definition.
  2. Override the constructor of the MyModelFrom, set the self.initial meh property if a model instance was passed to the form.
  3. Override the save method of the MyModelFrom, set the meh property on the model instance based on the form fields.

This way, the meh property would be correctly filled at your Model, but you'll also need to override MyModel's save() method to actually persist this value to your disk file:

(Google for "django model override save", sry, it seems I can't post more than a link per answer till I get more than 10 rep...)

Cheers,

Upvotes: 1

victorhooi
victorhooi

Reputation: 17275

Ny Django knowledge isn't that great, but depending on how complicated you want it to be, I'm not sure something like this can be easily done without much hackery.

Anyhow, if you want to add it to Add MyModel page, you can edit the appropriate admin template.

So in your template directory, create something like:

admin/app_label/MyModel/change_form.html

Then extend the base template, and add your own content:

{% extends "admin/change_form.html" %}

{% block something_you_want_to_override %}
    <p>Your HTML goes here</p>
{% endblock %}

Is there really no way you can get this custom field into an actual Django field though? Surely you can override the save() method on the model and do it that way? Or use a pre_save signal?

Cheers, Victor

Upvotes: 1

Related Questions