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, I would add the "fallback" message to the template only. You can do so with the default
template filter:
{{ object.notes | default:"<i>No notes</i>" }}
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_notes
function that adds some sort of placeholder.
I would suggest that "No notes"
is not the content of the CharField
. 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 a placeholder
, and add relevant markup for that:
class SomeForm(forms.Form):
notes = forms.CharField(
label='notes',
widget=forms.TextInput(attrs={'placeholder': 'No notes'})
)
You can then perform markup with a .css
stylesheet:
input::placeholder {
font-style: italic;
}
get_notes
insteadIn case you insist on using get_notes
, you can first of simplify your function, and furthermore you can use mark_safe(..)
to render raw html:
from django.utils.safestring import mark_safe
def get_notes(self):
return self.notes or mark_safe('<i>No notes</i>')