У объекта 'QuerySet' нет атрибута 'x'

Я хочу перейти на страницу пользователя и посмотреть его фотографии, поэтому я пытался получить объекты, назначенные внешнему ключу, но я продолжаю получать ошибку выше AttributeError at /user/30/ У объекта 'QuerySet' нет атрибута 'file'. Мне кажется, что проблема в моем синтаксисе, но я действительно не могу понять, почему он не может прочитать мой объект файловой модели Uploads, но может прочитать объекты моего профиля.

views.py

def profile_view(request, *args, **kwargs,):
    #users_id = kwargs.get("users_id")
    #img = Uploads.objects.filter(profile = users_id).order_by("-id")
    context = {}
    user_id = kwargs.get("user_id")
    try:
        profile = Profile.objects.get(user=user_id)
        img = profile.uploads_set.all()
    except:
        return HttpResponse("Something went wrong.")
    if profile and img:
        context['id'] = profile.id
        context['user'] = profile.user
        context['email'] = profile.email
        context['profile_picture'] = profile.profile_picture.url
        context['file'] = img.file.url


        return render(request, "main/profile_visit.html", context)

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete = models.CASCADE, null = False, blank = True)
    first_name = models.CharField(max_length = 50, null = True, blank = True)
    last_name = models.CharField(max_length = 50, null = True, blank = True)
    phone = models.CharField(max_length = 50, null = True, blank = True)
    email = models.EmailField(max_length = 50, null = True, blank = True)
    bio = models.TextField(max_length = 300, null = True, blank = True)
    profile_picture = models.ImageField(default = 'default.png', upload_to = "img/%y", null = True, blank = True)
    banner_picture = models.ImageField(default = 'bg_image.png', upload_to = "img/%y", null = True, blank = True)

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



class Uploads(models.Model):
    album = models.ForeignKey('Album', on_delete=models.SET_NULL,null=True,blank=True)
    caption = models.CharField(max_length = 100, blank=True, null = True)
    file = models.FileField(upload_to = "img/%y", null = True)
    profile = models.ForeignKey(Profile, on_delete = models.CASCADE, default = None, null = True)
    id = models.AutoField(primary_key = True, null = False)


    def __str__(self):
        return str(self.file) and f"/single_page/{self.id}"

class Album(models.Model):
    name=models.CharField(max_length=400)

Это:

img = profile.uploads_set.all()

является кверисетом, поэтому у него нет атрибута file.

Вы можете перебирать его, и его отдельные члены будут иметь атрибут file.

url_list = []
for i in img:
    url_list.append(i.file.url)

затем предоставит вам список нужных URL-адресов.

Вы также можете сделать это в виде понимания списка:

url_list = [i.file.url for i in img]

img = profile.uploads_set.all() отсюда img - это кверисет. а файл - это поле экземпляра выгрузки.

вы можете сделать следующее.

context['file'] = [im.file.url for im in img]

таким образом вы можете получить все файлы для профиля.

Вернуться на верх