-1

I have a list of events (with links) that I want to show as comma separated like

event1, event2, event3

I tried the solution here but not working for me.

Here is the code :

<p> 

  {% for element in event.getelement.all() %}

       <a href="{{ build_absolute_url(url('main:home_getlink',link.uri)) }}">
        {{ element }} </a> 
     {% endfor %} 
</p>
Community
  • 1
  • 1
user2714823
  • 607
  • 5
  • 15
  • 29

2 Answers2

1

Do:

<p> 
  {% for element in event.getelement.all %}
      <a href="{{ build_absolute_url(url('main:home_getlink',link.uri)) }}">
        {{ element }}
      </a>{% if not forloop.last %}, {% endif %}
  {% endfor %} 
</p>

Also, what's up with that href? Are you not using named routes whereby you can simply leverage the {% url [route-name] [params] %} tag?

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
0

This shouldn't be a function call since it is inside template. Change below,

{% for element in event.getelement.all() %}

with

{% for element in event.getelement.all %}

And for rest, the solution link you've posted should work after that.


Edit:

If you do this,

{{ event.getelement.all|join:", " }}

So this might produce result something like,

GetElement object, GetElement object, GetElement object

to get the value of a specific attribute you have to add the attribute as well. Something like this,

{% for e in event.getelement.all %}
    {{ e.<attr_name> }},
{% endfor %}

And this might produce something like,

event1, event2, event3,

Of course this is not an optimal solution because this is not the right way to do things when using any Framework.


Optimal solution:

What should be followed is that, do each and every logic in your views and send clean (pure) form of data to your templates. I mean send lists, dictionaries, objects, tuples should be sent to the templates. Hence creating a list of all the events and sending it templates though context.

Note: Following example is all based on assumptions.

View:

def xyz(request):
    event = Event.objects.get(name='xyz')
    context = {
       'event_elements': [e.name for e in event.getelement.all()]
    }

    return render(request, 'xyz.html', context)

Template:

{{ event_elements|join:", " }}

Now this will definitely work.

Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47