'Django HTML form: how can I only populate a field value if it exists?
My Django application has a Person model with some optional text fields, such as:
nickname = models.CharField(max_length=20, null=True, blank=True, default='')
When a record doesn't have one of these fields populated, it just appears empty in the Django Admin (as expected).
I have a little form where a person can update some select fields on the record, and the field appears on the form like so (prefilling the field with the current value):
<label class="col-form-label mt-4" for="nickname">Nick name:</label>
<input type="text" class="form-control" value="{{ person.nickname }}" id="nickname" name="nickname">
The Problem:
For a record where the field is empty, 'None' is shown as the value on the form field, and if you submit the form without removing it, the record is updated with the string 'None' saved for that field. How can I update my code so the form only pre-fills that 'value' if there's actually an existing value to use?
Solution 1:[1]
You should use the default_if_none
template tag. See the doc here
A quick example of how to use it would be the following:
{{ value|default_if_none:""}}
Solution 2:[2]
Try this:
<input type="text" class="form-control" value="{%if person.nickname %} person.nickname {% endif %}" id="nickname" name="nickname">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Frédéric Perron |
Solution 2 | Peter Mortensen |