Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3997358
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T07:23:31+00:00 2026-05-20T07:23:31+00:00

I wrote this little function for writing out HTML tags: def html_tag(tag, content=None, close=True,

  • 0

I wrote this little function for writing out HTML tags:

def html_tag(tag, content=None, close=True, attrs={}):
    lst = ['<',tag]
    for key, val in attrs.iteritems():
        lst.append(' %s="%s"' % (key, escape_html(val)))
    if close:
        if content is None: lst.append(' />')
        else: lst.extend(['>', content, '</', tag, '>'])
    else:
        lst.append('>')
    return mark_safe(''.join(lst))

Which worked great, but then I read this article on efficient string concatenation (I know it doesn’t really matter for this, but I wanted consistency) and decided to update my script:

def html_tag(tag, body=None, close=True, attrs={}):
    s = StringIO()
    s.write('<%s'%tag)
    for key, val in attrs.iteritems():
        s.write(' %s="%s"' % (key, escape_html(val)))
    if close:
        if body is None: s.write(' />')
        else: s.write('>%s</%s>' % (body, tag))
    else:
        s.write('>')
    return mark_safe(s.getvalue())

But now my HTML get escaped when I try to render it from my template. Everything else is exactly the same. It works properly if I replace the last line with return mark_safe(unicode(s.getvalue())). I checked the return type of s.getvalue(). It should be a str, just like the first function, so why is this failing??

Also fails with SafeString(s.getvalue()) but succeeds with SafeUnicode(s.getvalue()).


I’d also like to point out that I used return mark_safe(s.getvalue()) in a different function with no odd behavior.


The “call stack” looks like this:

class Input(Widget):
    def render(self):
        return html_tag('input', attrs={'type':self.itype, 'id':self.id,
            'name':self.name, 'value':self.value, 'class':self.itype})
class Field:
    def __unicode__(self):
        return mark_safe(self.widget.render())

And then {{myfield}} is in the template. So it does get mark_safed‘d twice, which I thought might have been the problem, but I tried removing that too….. I really have no idea what’s causing this, but it’s not too hard to work around, so I guess I won’t fret about it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T07:23:32+00:00Added an answer on May 20, 2026 at 7:23 am

    The render method of your widget is called by the BoundField.__unicode__ function, which returns SafeString instead (of a subclass of unicode.)

    Many places in Django (e.g. django.template.VariableNode.render) will actually call force_unicode on the field instance itself. This will have the effect of doing unicode(instance.__unicode__()), so even though instance.__unicode__() returns a SafeString object, it will become a regular unicode object.

    To illustrate, have a look at the snippet below:

    from django.utils.encoding import force_unicode
    from django.utils.safestring import mark_safe
    
    class Foo(object):
        def __unicode__(self):
            return mark_safe("foo")
    
    foo = Foo()
    print "foo =", type(foo)
    
    ufoo = unicode(foo)
    print "ufoo =", type(ufoo)
    
    forced_foo = force_unicode(foo)
    print "forced_foo =", type(forced_foo)
    
    
    bar = mark_safe("bar")
    print "bar =", type(bar)
    
    forced_bar = force_unicode(bar)
    print "forced_bar =", type(forced_bar)
    

    Output:

    foo = <class 'testt.Foo'>
    ufoo = <type 'unicode'>
    forced_foo = <type 'unicode'>
    bar = <class 'django.utils.safestring.SafeString'>
    forced_bar = <class 'django.utils.safestring.SafeUnicode'>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm just mucking around with C as a learner, and wrote this little function
I have this little function function makewindows(){ child1 = window.open (about:blank); child1.document.write(<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']),
First a little intro: Last year i wrote this http://dragan.yourtree.org/code/canvas-3d-graph/ Now, i want to
I wrote this function that's supposed to do StringPadRight("Hello", 10, "0") -> "Hello00000" .
I am just starting out with writing jQuery plugins. I wrote three small plugins
I made a little helper function: import zipfile def main(archive_list=[],zfilename='default.zip'): print zfilename zout =
So I wrote up this little peace of code as practice for myself... But
I wrote this little snippet that should format money but its failing on the
I wrote this snippet of code and I assume len is tail-recursive, but a
I wrote this code I have these errors Cannot implicitly convert type x.Program.TreeNode' to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.