Karthik
Karthik

Reputation: 77

Django Replace with space from underscore in templates

In my database jobs table, state field having values "New_Mexico". But I need to display in html page like "New Mexico". Give some ideas for find and replace.

views.py

def result(request,user_id):
    userid=user_id
    query = Q(emp__companyname=userid) | Q(state=userid )
    details=jobs.objects.filter(query).select_related()
    return render_to_response('result.html', {'details': details})

result.html

{% for d in details %}
    <label>{{ d.state }}</label>
{% endfor %}

Upvotes: 6

Views: 14476

Answers (3)

jahurul25
jahurul25

Reputation: 159

If your text is "python program language"

After use this code in your html in django {{ data.value.split|join:"-" }}

Answer is : python-program-language

Upvotes: 4

mawimawi
mawimawi

Reputation: 4343

If this should be the default output when using {{ object }}, then you should override the __unicode__ method of your model like this:

class MyModel(models.Model):
  title = models.CharField(...)  # this field may hold our string "New_Mexico"
  ...
  def __unicode__(self):
    return self.title.replace('_', ' ')

A different approach might be using {{ object.human_readable_title }}, where you define a method in your model:

  def human_readable_title(self):
    return self.title.replace('_', ' ')

I see no reason to build your own template tag for this use case, except you want to use it for many fields of different models.

EDIT: It seems you have a field called "state" in your "jobs" class. So in your case, a solution might be: in your model class create a method

def human_readable_state(self):
  return self.state.replace('_', ' ')

and in the template use:

<label>{{ d.human_readable_state }}</label>

That should do the trick.

Upvotes: 9

Akshar Raaj
Akshar Raaj

Reputation: 15221

There is no built-in template tag or filter to do this.

Write your own template filter.

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters explains what you want.

Upvotes: 2

Related Questions