Moritz_1201
Moritz_1201

Reputation: 17

Django searching for user with url

I have a problem with django. I try to search for users by getting an inputvalue and append this value to my url, so that one can basically search by typing a name in the url too (like it is by Instagram). For example: "localhost/name", it gives me all information to the User. Although the value is in the url and I have a dynamic url function, it doesn´t work. I read a lot of questions here but none worked for me. Thanks in advance.

urls.py

path("<str:name>/", views.search, name="search"),

views.py

@login_required(login_url="login")
def search(response, name=None):


if response.method == "POST":
    searched = response.POST['searchinput']
    users = User.objects.filter(username=name)
    return render(response, "main/search.html", {"searched":searched, "user":users})

else:
    return redirect("home")

base.html (for the input)

              <form id="searchform" class="form-inline my-2 my-lg-0" name="searchinputform" method="POST" action=" {% url 'search' name=None %}">
              {% csrf_token %}
              <input class="form-control mr-sm-2" type="search" name="searchinput" id="searchinput" placeholder="Suche" >

<script>
$( "#searchform" ).submit( function( e ) {
    e.preventDefault();

    document.location = $( "#searchinput" ).val();

  } );
</script>

Upvotes: 0

Views: 414

Answers (2)

Ali Aref
Ali Aref

Reputation: 2402

i think you want something like this

# urls.py
path("<str:name>/", views.search, name="search")

# views
@login_required(login_url="login")
def search(request, *args, **kwargs):
    name = kwargs.get("name")
    users = User.objects.filter(username=username)
    if users.exists():
        return render(request, "main/search.html", {"searched":searched, "users":users})
    else:
        return redirect("home")

or if you want it for single user

# used username instated of name so it be more clear,
# and because names are not unique but usernames are.
path("<str:username>/", views.search, name="search")

# views
@login_required(login_url="login")
def search(request, *args, **kwargs):
    username = kwargs.get("username")
    user = User.objects.filter(username=username)
    if user.exists():
        return render(request, "main/search.html", {"searched":searched, "user":user.first()})
    else:
        return redirect("home")

Upvotes: 1

Alex Paramonov
Alex Paramonov

Reputation: 2710

This code

    users = User.objects.filter(username=name)

will give you not a single user but a list of users. If you need just one user that matches by username change it to

    user = User.objects.get(username=name.strip())

or

    user = User.objects.filter(username=name).first()

Upvotes: 0

Related Questions