cyberspider789
cyberspider789

Reputation: 391

Foreign key issue in UserProfile django

I want to retrieve User profile data of User who is logged in. e.g. Based on logged in user I want to retrieve the country of the user from userprofile. Seems straightforward but I am missing some fine print. Tried a lot but no success.

Need help. I tried and referred django document but I am a newbie

I am having following model.

class User(AbstractUser):
    username = models.CharField(max_length=100,blank=True, null=True)
    email = models.EmailField(_('email address'), unique=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username', 'first_name', 'last_name']

    def __str__(self):
        return "{}".format(self.email)

class UserProfile(models.Model):
 user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile')
    title = models.CharField(max_length=5)
    dob = models.DateField()
    address = models.CharField(max_length=255)
    country = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    zip = models.CharField(max_length=5)
    photo = models.ImageField(upload_to='uploads', blank=True)

Upvotes: 0

Views: 282

Answers (1)

Naveen Jain
Naveen Jain

Reputation: 1072

when request comes to view functionality of django it has parameter called request.user. this is an apporach you should use.

if(request.user and request.user.is_authenticated()): 
    user_profile = UserProfile.objects.get(user=request.user)
    user_country = user_profile.country

or if you use a OneToOneField

request.user.userprofile.country

Suggestion:
1. When using custom user model define custom manager also.
2. relation should be OneToOneField between User and UserProfile.

Explaination of above code.
I used objects.get() But according to your model objects.filter() you should use because ForeignKeyField has many-to-one relationship.so same user may have many user profiles.

Upvotes: 1

Related Questions