简体   繁体   中英

Custom rendering of foreign field in form in django template

In my modelform I have a foreign key, I cannot figure out how to change the appearance of this field in template. I can change the text by changing

__unicode__ 

of the model, but how would I make it bold, for example?

in models.py I tried the following but form renders with and all other tags as if they were just text:

def __unicode__(self):
    u'<b>Name</b>: {}\n<b>Loyal</b>: {}'.format(self.name, self.loyal)

my template.html :

  <form method="post">
    {% csrf_token %}
    {{ form.client|safe}} 
    <br>
    <input type="submit" value="Save changes" class="btn btn-s btn-success">
  </form>

doesn't work.

Here is the picture:

在此处输入图片说明

Django 1.9 has a format_html function that might be what you are looking for. From the Docs :

format_html(format_string, *args, **kwargs)

This is similar to str.format(), except that it is appropriate for building up HTML fragments . All args and kwargs are passed through conditional_escape() before being passed to str.format().

For the case of building up small HTML fragments, this function is to be preferred over string interpolation using % or str.format() directly, because it applies escaping to all arguments - just like the template system applies escaping by default.

More information here: Prevent django admin from escaping html

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