Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override field value display in Django admin change form

How can I override the value that is displayed for a field in the Django admin? The field contains XML and when viewing it in the admin I want to pretty-format it for easy readability. I know how to do reformatting on read and write of the field itself, but this is not what I want to do. I want the XML stored with whitespace stripped and I only want to reformat it when it is viewed in the admin change form.

How can I control the value displayed in the textarea of the admin change form for this field?

like image 272
gbutler Avatar asked Aug 13 '12 20:08

gbutler


People also ask

How do I override a field in Django admin?

The way to override fields is to create a Form for use with the ModelAdmin object. This didn't work for me, you need to pass an instance of the widget, rather than the class. The instance worked perfectly, though. I typically would create custom admin forms in the admin.py and not mix them in with forms.py.

How do I override a form in Django?

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.

How do you make a field non editable in Django admin?

editable=False will make the field disappear from all forms including admin and ModelForm i.e., it can not be edited using any form. The field will not be displayed in the admin or any other ModelForm.


1 Answers

class MyModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.initial['some_field'] = some_encoding_method(self.instance.some_field)

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
    ...

Where, some_encoding_method would be something you've set up to determine the spacing/indentation or some other 3rd-party functionality you're borrowing on. However, if you write your own method, it would be better to put it on the model, itself, and then call it through the instance:

class MyModel(models.Model):
    ...
    def encode_some_field(self):
        # do something with self.some_field
        return encoded_some_field

Then:

self.instance.encode_some_field()
like image 129
Chris Pratt Avatar answered Nov 11 '22 15:11

Chris Pratt