Reputation: 57
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>
Upvotes: 1
Views: 702
Reputation: 1069
You can use the request object to find the logged in user i.e. request.user
Upvotes: 1
Reputation: 476689
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):
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.
Note: according tot PEP 8, one uses lowercase characters and an underscore as separator for functions, so it is probably better to rename
ProfileView
toprofile_view
, as I did here.
Upvotes: 1