我有一个连接到模型的用户配置文件页面,其中包含以下字段:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
这就像它应该的那样工作;连接到有问题的用户的配置文件图像被加载,并且用户之间的区别被区分。 我现在要做的是将一个单独的图库模型连接到个人资料页面,这样用户可能会有一个小的图像图库。 gallery模型如下所示:
class GalleryModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
img_1 = models.ImageField(default='default.jpg', upload_to='images')
img_2 = models.ImageField(default='default.jpg', upload_to='images')
img_3 = models.ImageField(default='default.jpg', upload_to='images')
那个视图.py文件如下所示:
class ProfileDetailView(DetailView):
model = Profile # Is something iffy here? Should this refer to the GalleryModel as well?
template_name = 'account/view_profile.html'
def get_object(self):
username = self.kwargs.get('username')
if username is None:
raise Http404
return get_object_or_404(User, username__iexact=username, is_active=True)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
username = self.object.username
context['person'] = GalleryModel.objects.get(user__username=username) #loads username string
context['img_1'] = GalleryModel.objects.last().img_1
context['img_2'] = GalleryModel.objects.last().img_2
context['img_3'] = GalleryModel.objects.last().img_3
return context
我试过很多想法(例如filter()和get()方法的各种方法),仔细检查https://docs.djangoproject.com/en/2.1/topics/db/queries/,筛选我能找到的东西,但是我没能解决。你知道吗
例如,filter(username\uu iexact=username)似乎不起作用,主题的变化也不会产生错误消息,但我并不真正理解。 如果我在模板中插入{{person}},我可以获得用户名,但是我如何获得连接到GalleryModel中用户名的对象(图像)?你知道吗
尝试以下方法是不可能的:
GalleryModel.objects.get(user__username=username).img_1
和往常一样,我有一种奇怪的感觉,我错过了一些相当简单的东西:)
注意!:我知道last()方法显然不是我应该做的,但到目前为止,它是我获得图像以渲染到模板的唯一方法。你知道吗
如果要将库连接到配置文件,则必须将配置文件添加为ForeignKey,而不是User。你知道吗
除非你有其他类型的画廊,使用画廊(模型。模型). 你知道吗
相关问题 更多 >
编程相关推荐