Create hyperlink in django template of object with space

I am trying to create a dynamic hyperlink that depends on the value passed from the function:

{% for item in field_list %} <a href={% url index_view %}{{ item }}/> {{ item }} </a> <br> {% endfor %} 

The problem is that one of the items in the list box is the “Hockey Player”. A link for some reason is to delete everything after a space, so it creates a hyperlink to the entire "Hockey player", but the address

 http://126.0.0.1:8000/Hockey 

How can I make him switch to

 http://126.0.0.1:8000/Hockey Player/ 

instead

+4
source share
3 answers

Use the urlencode filter.

 {{ item|urlencode }} 

But why do you take the name? You must pass the appropriate view and PK or slug to the url , which itself will create a suitable URL.

+6
source

Since spaces are illegal in URLs,

 http://126.0.0.1:8000/Hockey Player/ 

unacceptably. The urlencode filter will simply replace the space with% 20, which is ugly / inelegant even if it does a certain job. A much better solution is to use the "slug" field in your model, which is a cleaned version of the header field (I assume this is called the header field). You want to get a clean URL, for example:

 http://126.0.0.1:8000/hockey_player/ 

To make this happen, use something like this in your model:

 class Player(models.Model): title = models.CharField(max_length=60) slug = models.SlugField() ... 

If you want the slug field to be pre-populated by the administrator, use something like this in admin.py:

 class PlayerAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} .... admin.site.register(Player,PlayerAdmin) 

Now when you enter the new Player in admin, if you type “Hockey Player” for Title, the Slug field will automatically become “hockey_player”.

In the template you should use:

 {% for item in field_list %} <a href={% url index_view %}{{ item.slug }}/> {{ item }} </a> <br> {% endfor %} 
+2
source

Source: https://habr.com/ru/post/1304418/


All Articles