OneToOneField Django inverse?… here is a solution to the problem.
OneToOneField Django inverse?
I’m using the user model
from django.contrib.auth.models import User
The UserProfile model extends the User model
class UserProfile(models. Model):
user = models. OneToOneField(User, related_name='userprofiles')
avatar = models. FileField('img',upload_to='./static/image/')
I
need to get the user’s avatar and I’m doing something similar
user = User.objects.get(pk=1)
user.userprofiles
But it throws an error
RelatedObjectDoesNotExist: User has no userprofile.
Tracking:
In [5]: user = User.objects.get(pk=1)
In [6]: user.userprofiles
---------------------------------------------------------------------------
RelatedObjectDoesNotExist Traceback (most recent call last)
<ipython-input-6-2253b19e792d> in <module>()
----> 1 user.userprofiles
C:\Program Files\Anaconda3\lib\site-packages\django\db\models\fields\related_des
criptors.py in __get__(self, instance, cls)
405 "%s has no %s." % (
406 instance.__class__.__name__,
--> 407 self.related.get_accessor_name()
408 )
409 )
RelatedObjectDoesNotExist: User has no userprofiles.
Solution
There are typos in the following:
user = models. OneToOneField(User, related_name='userprofiles')
# userprofiles with 's'
However, you have tried to access it using user.userprofile
without s
Either remove the
s in related_name=’userprofiles’ or add s
: –> user.userprofiles to access Userprofile
.