views:

170

answers:

3

I am trying to create a dynamic hyperlink that depends on a value passed from a 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 field_list is "Hockey Player". The link for some reason is dropping everything after the space, so it creates the hyperlink on the entire "Hockey Player", but the address is

http://126.0.0.1:8000/Hockey

How can I get it to go to

http://126.0.0.1:8000/Hockey Player/

instead?

+2  A: 

There is this builtin filter .

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#urlencode

Although you should be using one of these

http://docs.djangoproject.com/en/dev/ref/models/fields/#slugfield

michael
Thanks, though I'm not sure I understand how the slugfield would be used or helps.
Ed
+2  A: 

Use the urlencode filter.

{{ item|urlencode }}

But why are you taking the name? You should be passing the appropriate view and PK or slug to url which will create a suitable URL on its own.

Ignacio Vazquez-Abrams
Django newbie here. Could you be more specific? I sort of get what you're suggesting, but I'm not quite there. . .
Ed
It's just as the docs say. Write a view, put it in urlconf, and use `url`. http://docs.djangoproject.com/en/dev/ref/templates/builtins/#url
Ignacio Vazquez-Abrams
A: 

Since spaces are illegal in URLs,

http://126.0.0.1:8000/Hockey Player/

is unacceptable. The urlencode filter will simply replace the space with %20, which is ugly/inelegant, even if it does kind of get the job done. A much better solution is to use a "slug" field on your model that represents a cleaned-up version of the title field (I'll assume it's called the title field). You want to end up with a clean URL like:

http://126.0.0.1:8000/hockey_player/

To make that 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 in the admin, use something like this in your admin.py:

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

admin.site.register(Player,PlayerAdmin)

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

In the template you would then use:

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