From 0b6041296778fe99983d75bd97e8e9d222fb9896 Mon Sep 17 00:00:00 2001 From: Evan Chen Date: Fri, 15 Sep 2023 14:25:47 -0400 Subject: [PATCH] feat(roster): improve discord_lookup --- roster/templates/roster/discord_lookup.html | 16 +++++++++ roster/views.py | 37 +++++++++------------ 2 files changed, 32 insertions(+), 21 deletions(-) diff --git a/roster/templates/roster/discord_lookup.html b/roster/templates/roster/discord_lookup.html index 2a8a9eae..9f5b8c31 100644 --- a/roster/templates/roster/discord_lookup.html +++ b/roster/templates/roster/discord_lookup.html @@ -1,6 +1,22 @@ {% extends "layout.html" %} {% block title %}Discord Lookup{% endblock %} {% block layout-content %} + {% if lookup != None %} +

Results

+ {% if lookup|length == 0 %} +
No matches were found.
+ {% else %} + + {% endif %} +
+ {% endif %} +

Lookup

Look up a student by Discord username.

{% include "generic_form.html" with submit_name="Search" %} {% endblock layout-content %} diff --git a/roster/views.py b/roster/views.py index 86bd4dd3..6d8baaa1 100644 --- a/roster/views.py +++ b/roster/views.py @@ -698,33 +698,28 @@ def link_assistant(request: HttpRequest) -> HttpResponse: @admin_required def discord_lookup(request: HttpRequest) -> HttpResponse: + context = {} if request.method == "POST": form = DiscordLookupForm(request.POST) if form.is_valid(): discord_handle = form.cleaned_data["discord_handle"] - try: - sa = SocialAccount.objects.get( - provider="discord", - extra_data__icontains=discord_handle, - ) - except SocialAccount.DoesNotExist: - messages.error(request, f"Could not find {discord_handle}.") - except SocialAccount.MultipleObjectsReturned: - messages.error( - request, - f"Somehow found multiple social accounts for {discord_handle}.", - ) - else: - user = sa.user - student = Student.objects.filter(user=user).order_by("-pk").first() + lookup: dict[SocialAccount, str] = {} + for sa in SocialAccount.objects.filter( + provider="discord", extra_data__icontains=discord_handle + ).select_related("user")[:3]: + student = Student.objects.filter(user=sa.user).order_by("-pk").first() if student is not None: - return HttpResponseRedirect(student.get_absolute_url()) + lookup[sa] = student.get_absolute_url() else: - return HttpResponseRedirect( - reverse("admin:auth_user_change", args=(user.pk,)) - ) - + lookup[sa] = reverse("admin:auth_user_change", args=(sa.user.pk,)) + if len(lookup) == 1: + _, url = list(lookup.items())[0] + return HttpResponseRedirect(url) + context["lookup"] = lookup + else: + context["lookup"] = None else: form = DiscordLookupForm() - context = {"form": form} + context["lookup"] = None + context["form"] = form return render(request, "roster/discord_lookup.html", context)