Hi, my name luigi from italy … my studing english , python , django, html, css, javascript.
My problem custom tags.
from django import template
from accounts.models import *
register = template.Library()
@register.filter(display_name='display_name')
def display_name(value):
if value == 1:
return User.first_name + ' ' + User.last_name
elif value == 2:
return User.last_name + ' ' + User.first_name
elif value == 3:
return User.username
html:
{{request.user.display_name|display_name}}
output:
<django.db.models.query_utils.DeferredAttribute object at 0x0000024B313A5310>
idea solved problem ??
The problem is that you’re trying to access the value from the Class, not the instance of the User currently logged in.
What you may want to do is to pass the user to the filter, not the display name, like this.
{{request.user|display_name}}
But now, your function will receive the User
instance as the value
variable. So you need to change it a bit.
from django import template
from accounts.models import *
register = template.Library()
@register.filter(display_name='display_name')
def display_name(value):
# value refers to the user, so it may be useful to rename this variable to "user" instead of "value"
# i will be keeping it on the same way
if value.display_name == 1:
return value.first_name + ' ' + value.last_name
# You now can figure it out the remaining by yourself, i know you can do it
Notice that on the if
it’s checking for display_name
that’s the attribute that’s going to have the values 1,2,3 (apparently)
@register.filter(display_name='display_name')
def display_name(value):
if value.display_name == 1:
return value.last_name + ' ' + value.first_name
elif value.display_name == 2:
return value.first_name + ' ' + value.last_name
elif value.display_name == 3:
return value.username
solution ok…
my problem in the code:
{% block content %}
<div id="users">
<div class="row">
{% for object in object_list %}
<div class="col-md-4 mb-3">
<div class="card">
<div class="card-body">
<img src="{% get_media_prefix %}{{ object.image.avatar }}">
</div>
<div class="card-footer">
<a href="{% url 'VediUtente' pk=object.id %}">
{{object.display_name|display_name}}
</a>
</div>
<div class="card-footer">
Iscrizione: <p>{{ object.date_joined|date:"d M Y" }}</p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
error:
‘int’ object has no attribute ‘display_name’
Idea solved ???
Thanks.