TemplateSyntaxError: Variable 'user.profile.photo' is an invalid source

TemplateSyntaxError: Variable 'user.profile.photo' is an invalid source

我无法通过 link 进行访问。我正在使用简易缩略图框架,并为用户列表创建了简单视图以列出所有现有用户。 错误信息:

django.template.exceptions.TemplateSyntaxError: Variable 'user.profile.photo' is an invalid source.

Django Traceback 让我看到这个视图。

views.py 文件:

@login_required
def user_list(request):
    users = User.objects.filter(is_active=True)
    return render(request,
                  'account/user/list.html',
                  {'section': 'people',
                   'users': users})

urls.py 文件:

path('users/', views.user_list, name='user_list'),

模板list.html:

{% extends "base.html" %}
{% load thumbnail %}

{% block title %}People{% endblock %}

{% block content %}
  <h1>People</h1>
  <div id="people-list">
    {% for user in users %}
      <div class="user">
        <a href="{{ user.get_absolute_url }}">
          <img src="{% thumbnail user.profile.photo 180x180 %}">
        </a>
        <div class="info">
          <a href="{{ user.get_absolute_url }}" class="title">
            {{ user.get_full_name }}
          </a>
        </div>
      </div>
    {% endfor %}
  </div>
{% endblock %}

示例代码来自 base.html:

 <li {% if section == "people" %}class="selected"{% endif %}>
 <a href="{% url "user_list" %}">People</a>
</li>

models.py:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE)
    date_of_birth = models.DateField(blank=True, null=True)
    photo = models.ImageField(upload_to='users/%Y/%m/%d/',
                              blank=True)

    def __str__(self):
        return f'Profile for user {self.user.username}'

提前感谢您的帮助。

查看文档 https://easy-thumbnails.readthedocs.io/en/latest/usage/#templates。从对象(通常是文件字段)创建缩略图。我试过了,它帮助解决了我的问题:

 <img src="{{ user.profile.photo.url }}">

我也有这个问题。您可以使用以下解决方案解决问题:

  1. 而不是users = User.objects.filter(is_active=True),使用profiles = Profile.objects.all()

  2. 修改如下:return render(request,'account/user/list.html',{'section': 'people', 'profiles': profiles}).

  3. list.html文件中,修改如下:

    {% extends 'base.html' %}
    {% load thumbnail %}
    
    {% block title %}People{% endblock %}
    
    {% block content %}
        <h1>People</h1>
        <div id="people-list">
            {% for profile in profiles %}
                <div class="user">
                    <a href="{{ profile.user.get_absolute_url }}">
                        <img src="{% thumbnail profile.photo 180x180 %}" alt="{{ profile.user.last_name }}">
                    </a>
                    <div class="info">
                        <a href="{{ profile.user.get_absolute_url }}" class="title">
                            {{ profile.user.get_full_name }}
                        </a>
                    </div>
                </div>
            {% endfor %}
        </div>
    {% endblock %}