Brandon Evans
Brandon Evans

Reputation: 59

Pass Django template variable in url template tag

I'm still a bit new to Django and have been stuck on trying to figure out a way to add a template variable to a Django url template tag.

I can better explain with an example...

I have a help center/knowledge base that currently has articles along with tags associated with that article. The goal is to allow users to click on those associated tags to perform a search on the help center using the tag that was clicked on and return a new set of articles in the search.

This is my url pattern:

urlpatterns = [
...
path('search/', views.search, name='search'),
...

]

My html:

<div id="tags uk-margin-bottom">
    {% for tag in article.tags.all %}
        <a href="{% url 'search' %}" class="badge badge-pill badge-primary">#{{ tag }}</a>
    {% endfor %}
</div>

My search view function:

def search(request):
if request.user.is_authenticated:        
    # get all articles
    queryset_list = Article.objects.all()

    if 'search' in request.GET:
        search = request.GET['search']

        if search:

            tags = []
            queryset_list_tags = queryset_list.filter(tags__name__icontains=search).distinct()

            try:
                queryset_list_title = queryset_list.filter(title__icontains=search).distinct()
            except:
                print("Testing - Couldn't grab titles.")

            search_results = queryset_list_tags | queryset_list_title

            # get all tags from query_list_title search
            for title in queryset_list_title:
                article = Article.objects.get(title=title)
                queryset_tags = article.tags.all().values_list('name')
         
                for tag in queryset_tags:
                    # add all tags in queryset to tags list
                    tags.append(tag[0])

            # get all tags from query_list_tags search
            for title in queryset_list_tags:
                z_article = Article.objects.get(title=title)
                z_queryset_tags = z_article.tags.all().values_list('name')
                
            
                for tag in z_queryset_tags:
                    # add all tags in queryset to tags list
                    tags.append(tag[0])

            # remove duplicate tags
            tags = list(dict.fromkeys(tags))
            print(f"tags: {tags}")

    context = {
        'articles': search_results,
        'tags': tags
    }

    return render(request, 'articles/search.html', context)
else:
    return redirect('/')

The search function works and lets users search for articles/tags in the database. The problem is, I need the search function to be called when a user clicks on a tag so that the URL would look like /articles/search/?search=thisisatag

I've tried adding a second parameter to the url pattern like this: path('search/<str:tag>', views.search, name='search'), but this ends up breaking the search feature everywhere else because a second parameter isn't needed anywhere but in this one instance (unless I'm misunderstanding something).

I can do this in the html but then my search function isn't called: <a href="/articles/search/?search={{tag}}" class="badge badge-pill badge-primary">#{{ tag }}</a>

Hopefully this makes sense - I'm still learning so any help or advice is greatly appreciated!

Upvotes: 1

Views: 1549

Answers (1)

Daniel
Daniel

Reputation: 3527

Something like this may work:

template.html:

<a href="{% url 'search' %}?search={{tag}}"> Go to </a>

views.py:

def search(request):

    # unpack GET parameters:
    tag = request.GET['search']

    ...

Upvotes: 4

Related Questions