Reputation: 73
I have a user profile page connected to a model which amongst other fields contain the following:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
That works like it should; the profile image connected to the user in question is loaded, and the distinction between users is made. What I'm trying to do now is connect a separate gallery model to the profile page, that the users may have a small image gallery to goof around with. The gallery model looks like this:
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')
The views.py file looks like this:
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
I've tried a bunch of ideas (i.e. various approaches to the filter() and get() methods) and scrutinizing https://docs.djangoproject.com/en/2.1/topics/db/queries/ and sifting through what I could find on SO, but I can't work it out.
For instance filter(username__iexact=username) doesn't seem to do the trick, nor do variations upon the theme produce anything but error messages, that I don't really understand. I can get the username to go through if I insert {{ person }} in the template, but how do I get the objects (images) connected to the username in the GalleryModel?
Trying for the following is a no go:
GalleryModel.objects.get(user__username=username).img_1
As always, I have an eerie feeling that I'm missing something rather simple :)
NB!: I know that the last() method is not what I'm supposed to do, obviously, but thus far it's the only way I've managed to get images to render unto the template.
Upvotes: 1
Views: 75
Reputation: 464
If you want to connect the Gallery to the Profile, you have to add Profile as ForeignKey, not User.
class GalleryModel(models.Model):
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
Except if you have another kind of Gallery, use Gallery(models.Model).
Upvotes: 2