简体   繁体   English

在Django中使用ID查找用户名

[英]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. 我想使用一个ID在我的数据库中搜索属于该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 我有一个url.py设置,以通过url变量提供id,然后将其传递到views.py并将其传递到模板

At the moment I have the following: 目前,我有以下内容:

models.py: 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 views.py

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

urls.py urls.py

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

profile.html 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 : 您需要获取该idUser对象:

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

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

We can then render it like: 然后我们可以像这样渲染它:

<img id="ProfileBox" src="../static/users/{{ user.username }}.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 . 如果使用静态文件 ,则最好使用{% static ... %}模板标记,如文档中所述。

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. 注意 :根据PEP 8 ,使用小写字符和下划线作为函数的分隔符,因此将ProfileView重命名为profile_view可能更好,就像我在这里所做的那样。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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