views.py
from .models import Profile
@login_required(login_url='/signin')
def settings(request):
user_profile=Profile.objects.get(user=request.user)
return render(request,'setting.html',{'user_profile':user_profile})
I think the error is in :user_profile=Profile.objects.get(user=request.user)
but I don't know why
models.py
from django.contrib.auth.models import User
from django.db import models
class Profile(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
id_user = models.IntegerField()
bio = models.TextField(blank=True)
profileimg = models.ImageField(upload_to='profile_pics/', default='default-profile.png')
location = models.CharField(max_length=300, blank=True)
birth_date = models.DateField(null=True, blank=True)
ERROR
CodePudding user response:
There may be a User
instance for the user you are trying to log in as, however that does not mean there is a Profile
present as well. You need to make sure every User
has a profile. There are a few ways to do it:
- (Recommended) Override the
save()
method onUser
to automatically create aProfile
when a new user is created. e.g:
class User(..):
# user properties
def save(self, *args, **kwargs):
if not self.pk:
Profile.objects.create(user=user)
super(MyModel, self).save(*args, **kwargs)
- Handle the action on the API call. So in your function you can check if the user has a profile, if they don't you may wish to create one. For example:
def settings(request):
user_profile=Profile.objects.get_or_create(user=request.user)
return render(request,'setting.html',{'user_profile':user_profile})
Here I used get_or_create
, but you are free to use try/except
blocks or whatever suits your backend logic best!