views:

351

answers:

1

Hi all,

In widget's code I need to get access to HTML id of the rendered element. I know I can run regexp on the rendered string and get the ID, but I believe there must be an easy way.

Let's assume this is the widget I have:

class TextInputWithHint(TextInput):
    ...
    def render(self, name, value, attrs):

        res = super(TextInputWithHint, self).render(name, value, attrs = attrs)
        res += mark_safe(u'<script type="text/javascript">alert(%s)</script>' \
        % self.attrs['id'])
        return res

Except that 'self.attrs['id']' does not work.

Is there an easy way to obtain ID in here?

Thanks!

+1  A: 

For your use case, you can find the id attribute in the attrs argument that is passed to render(). It is a good idea to check for its existence before trying to use it:

def render(self, name, value, attrs=None):
  # ...
  if attrs and 'id' in attrs:
    # Use attrs['id']
Ayman Hourieh
Is there a way to find it in the Django template language instead of rendering in Python?
dfrankow