gpt4 book ai didi

python - 在 django 中使用 id 查找用户名

转载 作者:行者123 更新时间:2023-12-01 01:10:59 25 4
gpt4 key购买 nike

我想使用一个 ID 在我的数据库中搜索属于该 ID 的用户名。

我有一个 url.py 设置,通过 url 变量提供 id,然后将其传递到将其传递给模板的views.py

目前我有以下内容:

模型.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/',)

View .py

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

url.py

path('profile/<int:id>', views.ProfileView, name='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>

最佳答案

您需要获取该 idUser 对象:

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

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

然后我们可以将其渲染为:

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

如果您使用静态文件,那么最好使用 {% static ... %} 模板标记,如 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.

关于python - 在 django 中使用 id 查找用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54873699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com