简体   繁体   中英

Finding an username using an id in django

I would like to use an id to search my database for the username that belongs to that id.

I have a url.py setup to give the id via an url variable then I pass it onto the views.py that passes it to the template

At the moment I have the following:

models.py:

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
     pass

def __str__(self):
    return self.email

docfile = models.FileField(upload_to='static/users/',)

views.py

def ProfileView(request, id):
    return render(request, 'pages/profile.html', {"id":id})

urls.py

path('profile/<int:id>', views.ProfileView, name='Profile')

profile.html

<div class="mainusers">
  <div class = "userLine">
   <p>{{ id.username }}</p> <!-- I know this wouldn't work, It's just a place holder at the moment -->
 <center><p></p><p class="mainfont"><u>{{ id.username }}</u><p></center>
  <div class="circular--portrait">
    <img id="ProfileBox" src="../static/users/{{ id.username }}.gif" onerror="this.onerror=null;this.src='static/users/default.gif';"/>
  </div>
  <center><p><br></br> Date Joined: {{id.date_joined}}</p></center>
  {% if id.is_superuser %}
    <center><p>Developer</p></center>
  {% endif %}
  <div class="wrapper">
    <button class="logout" onclick="window.location.href='{% url 'logout' %}'">Logout</button>
    <button class="logout" onclick="window.location.href='/invgen'">Generate Invite Code</button>
  </div>

You need to fetch the User object for that id :

from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404

def profile_view(request, id):
    
    return render(request, 'pages/profile.html', {'id':id, 'user': user})

We can then render it like:

<img id="ProfileBox" src="../static/users/{{  }}.gif" onerror="this.onerror=null;this.src='static/users/default.gif';"/>

If you make use of static files , it is however probably better to use the {% static ... %} template tag, as is described in the documentation .

Note : according tot PEP 8 , one uses lowercase characters and an underscore as separator for functions, so it is probably better to rename ProfileView to profile_view , as I did here.

您可以使用request对象查找已登录的用户,即request.user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM