0

I need something like that function for Django.

Reason: I write widget with separate config for admin and other pages. Config determined in custom field:

class Article(models.Model):
    field = CustomField(config={'default': {}, 'admin': {}})

For this reason I can't extend AdminTextareaWidget with my widget (part of current code below). Or can I? How?

class CustomField(TextField):
    def __init__(self, config, *args, **kwargs):
        self.config = dict_merge(initial_config, config)
        super(CustomField, self).__init__(*args, **kwargs)
    def formfield(self, **kwargs):
        ###################################
        # need to check for admin page here
        ###################################
        defaults = {'widget': CustomWidget(self.config)}
        defaults.update(kwargs)
        return super(CustomField, self).formfield(**defaults)

class CustomWidget(Textarea):
    def __init__(self, config, attrs=None):
        #########
        # or here
        #########
        self.config = config
        super(CustomWidget, self).__init__(attrs)
lampslave
  • 1,431
  • 1
  • 15
  • 20
  • I'm sorry, I misunderstood your question. I will delete my answer since it does not relate. I guess I don't quite understand your question then. How are you using `CustomField`? – jproffitt Sep 21 '13 at 00:38
  • What are you meant for "using"? It's just field like models.TextField... – lampslave Sep 21 '13 at 01:03
  • You clarified it. thanks. I'm thinking you're going to have to do the custom stuff in the view, where you can access the current url. So after you initialize the form, you can change the widgets. I would guess you would need to do it there. – jproffitt Sep 21 '13 at 01:10
  • But it isn't universal :( I want determine it once and allow the use of different configs for different fields. – lampslave Sep 21 '13 at 01:21

1 Answers1

0

I think I found the answer!
Maybe this is hack, but it works.

def formfield(self, **kwargs):
    # kwargs contain a widget name in admin! At least in Django 1.5.4.
    if 'widget' in kwargs and kwargs['widget'] is AdminTextareaWidget:
        config = self.config['admin']
    else:
        config = self.config['default']
    defaults = {'widget': CustomWidget(config)}
    defaults.update(kwargs)
    return super(CustomField, self).formfield(**defaults)
lampslave
  • 1,431
  • 1
  • 15
  • 20