[Answer]-Django template tag "if" statement not evaluating correctly trying a simple search

1👍

matches = RegisterProfile.objects.filter(
     Q(user__username__icontains=q)
    |Q(last_name__icontains=q)
    |Q(first_name__icontains=q)
)

<p>The following members matched your search results:</p>
{% for profile in matches %}
<li>Username: {{ profile.user.username }} Name: {{ profile.first_name }} {{ profile.last_name }}</li>
<li>q is in 
    {% if q in profile.user.username %}username, {% endif %}
    {% if q in profile.first_name %}first name, {% endif %}
    {% if q in profile.last_name %}last name.{%endif%}
</li>
{% endfor %}

This could be cleaned up some, but the building blocks are there. For instance, if q is just in username you will get a line like “q is in username,”. Also, I’ve assumed that RegisterProfile is your user profile, so I left out the profile.user.get_profile bit. If that isn’t the case, you may need to re-add that.

I think the key piece you were missing is the Q object stuff. Those allow you to do more complex things than ‘AND’ in your filters.

Leave a comment