Python 在django中使用id查找用户名
我想使用一个id在我的数据库中搜索属于该id的用户名 我有一个url.py设置,通过url变量提供id,然后我将其传递到views.py,后者将其传递到模板 目前,我有以下几点: models.py:Python 在django中使用id查找用户名,python,django,Python,Django,我想使用一个id在我的数据库中搜索属于该id的用户名 我有一个url.py设置,通过url变量提供id,然后我将其传递到views.py,后者将其传递到模板 目前,我有以下几点: models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass def __str__(self): r
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})
url.py
path('profile/<int:id>', views.ProfileView, name='Profile')
path('profile/',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>
{{id.username}}
{{id.username}}
加入日期:{id.Date\u Joined}
{%如果id.is_superuser%}
显影剂
{%endif%}
注销
生成邀请代码
您需要获取该
id的用户对象:
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})
来自django.contrib.auth.models导入用户
从django.shortcuts导入get\u对象\u或\404
def配置文件视图(请求,id):
用户=获取对象或404(用户,pk=id)
返回呈现(请求'pages/profile.html',{'id':id',user':user})
然后我们可以将其渲染为:
<img id="ProfileBox" src="../static/users/{{ user.username }}.gif" onerror="this.onerror=null;this.src='static/users/default.gif';"/>
user.username}.gif“onerror=”this.onerror=null;this.src='static/users/default.gif';“/>
但是,如果使用静态文件,则最好使用{%static…%}
模板标记,如中所述
注意:根据tot,我们使用小写字符和下划线作为函数分隔符,因此最好将ProfileView
重命名为profile\u view
,就像我在这里做的那样
您可以使用请求对象查找登录用户,即request.user