简体   繁体   中英

How to add more space in `__str__` method of Django model?

I want to add more spaces to __str__ method, but method cut off spaces to 1.

For example:

class Spam(models.Model):
    foo = models.IntegerField()
    bar = models.IntegerField()

    def __str__(self):
        return 'more spaces {}            {}!'.format(self.foo, self.bar)

This output in Django admin: more spaces 1 2

I want : more spaces 1 2

How do this?

If you use the print method it prints ok.

I guess you have a problem with html? Replace whitespaces with   (but then it looks like crap in the shell) or try a more explicit representation in admin...

Or you could try wrapping the string in the <pre> tag

I am not familiar with django, but you are checking the results at web-page, indeed.

So full answer for your question will be: You should use special HTML symbols for HTML-page to indent your second part of text. You can check special symbols here: http://www.wikihow.com/Insert-Spaces-in-HTML

To use '&nbsp' you can do:

def __str__(self):
    space_sym = "&nbsp"*10 # hardcode magic-number of indent spaces
    return 'more spaces {}{}{}!'.format(self.foo, space_sym, self.bar)

Where ever your str resides:

from django.utils import safestring

def __str__(self):
    string = safestring.mark_safe("more spaces {}"+"&nbsp;"*10+ "{}!".format(self.foo, self.bar))
    return string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM