Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to obtain a specific data from model in profile when person is logged in, Django?

I want to post a specific data in profile from user that is logged in.
I have a model like this:

class Customer(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=60)
    email = models.EmailField(max_length=100)

class Wallet(models.Model):
    name = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    usd = models.FloatField(null=True)

If for example ‘user2’ is logged in, and in database he has 10usd, I want in his profile to be shown 10usd.

But I don’t know how to request a specific data of user that is logged in


Views.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@login_required(login_url='main')
def profile_user(request):
    usd = wallet.objects.get (get his usd from db)
    return render(request, 'profile.html', {'usd':usd})

Thank you very much.

>Solution :

you can get logged in user’s id like this

user_id = request.user.id

then you can use it to fetch wallet details of that user

@login_required(login_url='main')
def profile_user(request):
    wallet_data= Wallet.objects.filter(name_id=user_id).values("usd").first()
    return render(request, 'profile.html', {'usd':wallet_data['usd']})

another recommendation keep field name Proper related to FK Table name.
like you set name = models.OneToOne for User.
you should set it like

class Wallet(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    usd = models.FloatField(null=True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading