1👍
✅
Solution to this problem.
The error occurs at this line
wallet = Wallet.objects.get(pk=request.user.userprofile.wallet_id_id)
Clearly because the userprofile doesn’t exist for the user. This can be for two main reasons.
- the user is the anonymous user (not authenticated) you are not checking if the user is logged in
- the user account was created before you created the user profile.
check if the profile exists first
if not getattr(request.user,'userprofile'):
# create user profile here
wallet = Wallet.objects.get(pk=request.user.userprofile.wallet_id_id)
The real solution
You have got your database design wrong. See this.
wallet = Wallet(username=request.POST['username'], amount=0)
This implies that you are having a username field in your wallet model, but then
class Userprofile(models.Model):
user = models.OneToOneField(User, unique=True, primary_key=True)
wallet_id = models.ForeignKey(Wallet, on_delete=models.CASCADE)
You have a wallet as a foreign key to a UserProfile which leads to a cyclic relationship.
The correct design would be to remove the username field from your Wallet and replace it with a user field
class Wallet(models.Model):
user = models.ForeignKey(User)
...
Then your user profile becomes
class Userprofile(models.Model):
user = models.OneToOneField(User, unique=True, primary_key=True)
date_ob = models.DateField(null=True, blank=True)
sex = models.CharField(max_length=1, null=True)
def __str__(self):
return self.user
👤e4c5
Source:stackexchange.com