Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

345
Visualizações
Querying the Sqlite database for a user with username "x" using the standard django.contrib.auth.models.User model

I'm trying to wrap my head around an issue I'm having.

I want to present the users with a page in which they can look up a user by entering his username.

Yet I can't wrap my head around how to do this. Do I provide a function in my view in which a query is executed that retrieves a user from the database? For example retrieve his username or id and go to his profile page? I can't seem to grasp how to do this, I have been looking for examples on this but I can't find anything so I hope someone here can help me out!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Yes, at the simplest level you would have a view that accepts a form submission which takes the value of the field and does something like User.objects.get(username=my_variable) and returns the results, if any. You should wrap the call in a try/ except block so your view doesn't blow up if no such user exists with that username. Django provides a shortcut function for doing just this, so instead of the line above you could do user = get_object_or_404(User, username=my_variable). Your whole view would look something like

from django.shortcuts import render, get_object_or_404

def username_search(request):
  # if there are any form values sent in a GET
  if request.GET:
    my_variable = request.GET.get('username', '')
    user = get_object_or_404(User, username=my_variable)
  else:
    user = None
  return render(request, 'some_template.html', {'user': user}

In reality you might also create a Django form to do some validation on the submissions and make it easier to render your form.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda