[英]Finding an username using an id in 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):
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>
您需要獲取該id
的User
對象:
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})
然后我們可以像這樣渲染它:
<img id="ProfileBox" src="../static/users/{{ user.username }}.gif" onerror="this.onerror=null;this.src='static/users/default.gif';"/>
如果使用靜態文件 ,則最好使用{% static ... %}
模板標記,如文檔中所述。
注意 :根據PEP 8 ,使用小寫字符和下划線作為函數的分隔符,因此將
ProfileView
重命名為profile_view
可能更好,就像我在這里所做的那樣。
您可以使用request對象查找已登錄的用戶,即request.user
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.