RadiantHex
RadiantHex

Reputation: 25587

Customizing Django form widgets? - Django

I'm having a little problem here!


I have discovered the following as being the globally accepted method for customizing Django admin field.

from django import forms
from django.utils.safestring import mark_safe

class AdminImageWidget(forms.FileInput):
    """
    A ImageField Widget for admin that shows a thumbnail.
    """

    def __init__(self, attrs={}):
        super(AdminImageWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        output = []
        if value and hasattr(value, "url"):
            output.append(('<a target="_blank" href="%s">'
                           '<img src="%s" style="height: 28px;" /></a> '
                           % (value.url, value.url)))
        output.append(super(AdminImageWidget, self).render(name, value, attrs))
        return mark_safe(u''.join(output))

I need to have access to other field of the model in order to decide how to display the field!

For example:

If I am keeping track of a value, let us call it "sales".

If I wish to customize how sales is displayed depending on another field, let us call it "conversion rate".

I have no obvious way of accessing the conversion rate field when overriding the sales widget!


Any ideas to work around this would be highly appreciated! Thanks :)

Upvotes: 2

Views: 1221

Answers (2)

Jiaaro
Jiaaro

Reputation: 76958

you probably want to use a custom form for the admin

Upvotes: 1

Gabriel Hurley
Gabriel Hurley

Reputation: 40082

You are correct that the widgets themselves are independent. My first thought for doing something more complex is to either provide a custom admin template that does what you want, or to pass in a piece of javascript code to handle the interrelated fields (much like how prepopulated fields work).

Upvotes: 1

Related Questions