Django: Get list item content from a list of hyperlinks

Viewed 113

I'm stuck with a list of anchor tags and getting their content to views.py.

Background: I have a input form for addresses. If the entered/submitted address is not specific as needed, for example because there are two cities with the same name, then I want to display a list of the potential addresses.

Therefore, I have prepared a list of the potential target addresses also with an anchor tag.

html page:

<ul>
<form action="{% url 'analytics' %}" method="GET">
{% for item in list_addresses %}
    <li><a href="{% url 'analytics' %}" name="pot_address" >{{ item.post_code }}</a></li>
{% endfor %}
</form>
</ul>

My urls.py:

urlpatterns = [
    path('', views.home, name = 'home'),
    path('/analytics', views.analytics, name = 'analytics'),
]

Now I want to pass the address (content of the list item in html) to my views.py file. The views.py file looks like this:

def analytics(request):
    if request.method == 'GET':
        pot_adress = request.GET['pot_address']

After having this address in views.py I want to use it to fetch specific data from a database.

Could somebody help me with this issue?

1 Answers

You need to add a query string to your URLs, so:

<a href="{% url 'analytics' %}?pot_code={{ item.post_code|urlencode }}" name="pot_address" >{{ item.post_code }}</a>

In the view, you can then filter with:

def analytics(request):
    if request.method == 'GET':
        pot_adress = request.GET['pot_address']
        SomeModel.objects.filter(post_code=pot_adress)
        # …
Related