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

Time:10-06

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

@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})

CodePudding user response:

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)

CodePudding user response:

Tu peux passez une class d'heritage avec AbstractUser

from django.contrib.auth.models import AbstractUser from django.db import models

class CustomUser(AbstractUser): pass # add additional fields in here

def __str__(self):
    return self.username

voir le lien

  • Related