TemplateSyntaxError: переменная user.profile.photo является недопустимым источником

У меня проблема с доступом по ссылке. Я использую структуру easy-thumbnail, и я создал простое представление для списка пользователей, чтобы перечислить всех существующих пользователей. Сообщение об ошибке:

django.template.exceptions.TemplateSyntaxError: переменная user.profile.photo является недопустимым источником.

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}'

Заранее благодарю за помощь.

2 ответа

Решение

Ознакомился с документацией https://easy-thumbnails.readthedocs.io/en/latest/usage/. Создает миниатюру из объекта (обычно из файлового поля). Я попробовал, и это помогло решить мою проблему:

 <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 %}
Другие вопросы по тегам