How to change the rendering of a certain type of field in a Django admin?

For example, I have IntegerField, and I want to change the way it is displayed to all Django administrators.

I have considered subclassing and overriding methods __str__and __unicode__, but this does not work.

class Duration(models.IntegerField):
    def __unicode__(self):
        return "x" + str(datetime.timedelta(0, self))
    def __str__(self):
        return "y" + str(datetime.timedelta(0, self))

Update: I just want to know how the field is displayed , not the edit control (widget) .

+3
source share
2 answers

I'm not sure what you want to do with this field, but if you want to change the displayed HTML code, you need to either change the widget that uses the form field, or create your own widget:

https://docs.djangoproject.com/en/dev/ref/forms/widgets/

models.py

class LovelyModel(models.Model):
    my_int = models.IntegerField()

forms.py

from widgets import WhateverWidgetIWant

class LovelyModelForm(forms.ModelForm):
    my_int = models.IntegerField(widget=WhateverWidgetIWant())

    class Meta:
        model = LovelyModel

admin.py

from forms import LovelyModelForm

class LovelyModelAdmin(admin.ModelAdmin):
    form = LovelyModelForm

?

+2

, - ( )::

import datetime
from django.db import models


class Duration(models.IntegerField):
    description = "Stores the number of seconds as integer, displays as time"
    def to_python(self, value):
        # this method can receive the value right out of the db, or an instance
        if isinstance(value, models.IntegerField):
            # if an instance, return the instance
            return value
        else:
            # otherwise, return our fancy time representation
            # assuming we have a number of seconds in the db
            return "x" + str(datetime.timedelta(0, value))
    def get_db_prep_value(self, value):
        # this method catches value right before sending to db
        # split the string, skipping first character
        hours, minutes, seconds = map(int, value[1:].split(':'))
        delta = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
        return delta.seconds

, , , Python, , . I.e., object.duration == 'x00:1:12', 72.

. .

+1

All Articles