视图中的Django外键 - 获取列表中每个用户显示的第一个图像

时间:2018-03-01 10:43:34

标签: python django foreign-keys

我正在尝试让我的信息中心显示您所在区域的用户列表。这到目前为止工作,但我不能得到用户的第一个图像显示。我得到的当前错误消息是“'QuerySet'对象没有属性'id'”

models.py

class Images(models.Model):
    image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png')
    user = models.ForeignKey(User, on_delete=models.CASCADE,  null=False)

views.py

class DashboardView(TemplateView):

    template_name = 've/cp/dashboard.html'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(DashboardView, self).dispatch(*args, **kwargs)


    def get(self, request, pk=None):
        users = User.objects.exclude(id=request.user.id)
        user = User.objects.filter(pk=pk)
        try:
            favorite = Favorite.objects.get(current_user=request.user)
            favorites = favorite.users.all()
        except Favorite.DoesNotExist:
            favorites = None

        args = {
            'users': users, 'favorites':favorites, 'images': Images.objects.filter(user_id=user.id)
        }

        return render(request, self.template_name, args)

dashboard.html

        <h2>People near you</h2>
        {% for user in users %}
            <a href="{% url 've:view_profile_with_pk' pk=user.pk %}">
                <h4>{{ user.username }}</h4>
                <p>{{ user.images }}</p>

            {% if images %}

                {% for img in images %}
                <a href="{{ img.image.url }}" target="_blank">
                <img src="{{ img.image.url }}" class="" style="max-width: 300px">
                </a>
                {% endfor %}
            {% else %}

            <p>No images</p>
            {% endif %}

            </a>

            {% if not user in favorites %}
            <a href="{% url 've:change_favorites' operation='add' pk=user.pk %}">
            <button type="button" class="btn btn-success">Add Favorite</button>
            </a>
            {% endif %}
        {% endfor %}

1 个答案:

答案 0 :(得分:3)

user = User.objects.filter(pk=pk)返回查询集。当你再试一次Images.objects.filter(user_id=user.id)时会引发错误。您需要使用first()方法获取queryset中的第一个对象:

user = User.objects.filter(pk=pk).first()

或者改为使用get

user = User.objects.get(pk=pk)

但如果提供了id的用户不存在,则第二个选项会引发DoesNotExist错误。要处理此错误,您可以使用get_object_or_404,如果ID错误,则返回找不到的页面:

from django.shortcuts import get_object_or_404
user = get_object_or_404(User, pk=1)