Home > Blockchain >  Get a single string attribute from my user's extended model
Get a single string attribute from my user's extended model

Time:10-20

i think my question it's simple, but i'm new and i cannot figure it out.

I have a user default Django model and my extended user model, and in my views.py i just want to get my logged user's address like a single string, i have been trying with different ways using (UserProfile.objects.values/filter/get etc...) but i just get errors.

Thank you for your time!

Models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    profile_pic = models.ImageField(null=True, blank=True, upload_to="profile_imgs")
    address = models.CharField(null=True, blank=True, max_length=150)
    curp = models.CharField(null=True, blank=True, max_length=18)

Views.py

@login_required(login_url='log')
def test(request):

address = "answer"

context = {
        'address': address,
    }

    return render(request, "test.html", context)

CodePudding user response:

You can fetch the address from the request user's instance but you need to add a related_name to the user field in UserProfile model.

see below:

user = models.OneToOneField(User, null=True, on_delete=models.CASCADE, related_name='user_profile')

after that fetch the request user's address in the view functions as follows:

@login_required(login_url='log')
def test(request):
    context = {
       'address': request.user.user_profile.address,
    }
    return render(request, "test.html", context)
  • Related