I have a field called notes in a model. If the field is empty, I want to output 'No notes' and I want to do it in italics. You can set the text to be 'No Notes' by using a get command in the models.py
def get_notes(self):
if len(self.notes) == 0:
return "No notes"
return self.notes
How do you have the html render as italics for the text 'No notes'.
Html:
<h6>Your Notes: </h6>
<p>{{ object.get_notes }}</p>
In case you render HTML
In case you render HTML, I would add the "fallback" message to the template only. You can do so with the
defaulttemplate filter:The advantage of this usage is that - in case another template should render another message, or the italics do not fit - you can decide to use something else. Furthermore the template is rather explicit on how the content should be rendered.
Note that we here thus use
.notes, not a.get_notesfunction that adds some sort of placeholder.In case of a form field
I would suggest that
"No notes"is not the content of theCharField. How would you destinguish"No notes"from a user explicitly writing"No notes"? What if you later change your mind? Then you have to rewrite all logic in forms, etc. You can however use aplaceholder, and add relevant markup for that:You can then perform markup with a
.cssstylesheet:Using
get_notesinsteadIn case you insist on using
get_notes, you can first of simplify your function, and furthermore you can usemark_safe(..)to render raw html: