I created a forum website. When pressing on a user profile i get and error in console that library.models.SiteUser.DoesNotExist: SiteUser matching query does not exist.
And in the browser it also displays: DoesNotExist at /profile/1/
SiteUser matching query does not exist.
Browser highlights this line userprof = SiteUser.objects.get(id=pk)
This is my views.py:
def userProfile(request, pk):
user = User.objects.get(id=pk)
**userprof = SiteUser.objects.get(id=pk)**
posts = user.post_set.all()
post_comments = user.comment_set.all()
interests = Interest.objects.all()
context = {
'user': user,
'userprof': userprof,
'posts': posts,
'post_comments': post_comments,
'interests': interests
}
return render(request, 'library/profile.html', context)
models.py:
class SiteUser(models.Model):
page_user = models.OneToOneField(User, on_delete=models.CASCADE)
about = HTMLField()
profile_pic = models.ImageField('profile_pic', upload_to='covers', null=True)
Any help would be greatly appreciated.
CodePudding user response:
If you have relations, then always use them if possible. Instead of getting SiteUser
having a User
pk
(it does not have to be always the same), get it using the relation between them:
# bad and risky
user = User.objects.get(id=pk)
userprof = SiteUser.objects.get(id=pk)
# good and always working if object exists
user = User.objects.get(id=pk)
userprof = user.siteuser
Good practice is to name related_name
argument for such usage:
class SiteUser(models.Model):
page_user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='foobar')
Then you can call it like:
user = User.objects.get(id=pk)
userprof = user.foobar
CodePudding user response:
User and SiteUser primary keys will not be same. You can easily get SiteUser from the following query:
userprof = user.siteuser # efficient solution
Or
userprof = SiteUser.objects.get(page_user_id=pk) # alternative solution but should not be used in this code sample
Because of their OneToOne relation. For more information, please check the documentation.