我想去用戶頁面查看他們的照片,所以我試圖將物件分配給外鍵,但我一直在 /user/30/ 'QuerySet' object has no attribute 處收到 AttributeError上方的錯誤檔案'。我覺得問題出在我的語法上,但我真的不知道為什么它無法讀取我的 Uploads 檔案模型物件,但它能夠讀取我的組態檔物件。
視圖.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)
模型.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)
uj5u.com熱心網友回復:
img = profile.uploads_set.all()從這里img是一個查詢集。file 是上傳實體的欄位。
您可以執行以下操作。
context['file'] = [im.file.url for im in img]
這樣您就可以獲得組態檔的所有檔案。
uj5u.com熱心網友回復:
這:
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432565.html
標籤:Python django django模型 django-views
