13👍
✅
There is no built-in tag or filter to do this replacement. Write a filter that splits by a given character, and then combine that with the join
filter, or write a filter that does the replacement directly.
93👍
A shorter version of Matthijs’ answer:
{{ user.name.split|join:"_" }}
Of course it only works when splitting on whitespace.
- [Django]-Is there a function for generating settings.SECRET_KEY in django?
- [Django]-How to write a Pandas DataFrame to Django model
- [Django]-Django admin: How to display the field marked as "editable=False" in the model?
10👍
I like to perform this type of conversions in my view / controller code i.e.:
user.underscored_name = user.name.replace(' ','_')
context['user'] = user
dont be afraid to just add a new (temporary) property and use this in your template:
{{ user.underscored_name }}
If you use this at more places add the method underscored_name to the User model:
class User()
def underscored_name(self):
return self.name.replace(' ','_')
- [Django]-Django – use reverse url mapping in settings
- [Django]-Reverse for '*' with arguments '()' and keyword arguments '{}' not found
- [Django]-Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."
4👍
If you dont like to write your own custom tag you could do it like this …
{% for word in user.name.split %}{{word}}{% if not forloop.last %}_{% endif %}{% endfor %}
However its quite verbose …
- [Django]-How to filter model results for multiple values for a many to many field in django
- [Django]-Django accessing ManyToMany fields from post_save signal
- [Django]-Django: Multiple forms possible when using FormView?
Source:stackexchange.com