1

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>
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Micah Pearce
  • 1,805
  • 3
  • 28
  • 61

1 Answers1

2

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 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.

In case of a form field

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;
}

Using get_notes instead

In 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>')
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thanks for the multiple ways of italicizing the notes; it's very useful to know. I'm going to go with the 'template-only' option. – Micah Pearce Jun 10 '18 at 18:23