Home > Mobile >  I got a query error when calling the user login in django
I got a query error when calling the user login in django

Time:07-12

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

enter image description here

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:

  1. (Recommended) Override the save() method on User to automatically create a Profile 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)
  1. 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!

  • Related