Home > other >  Field 'id' expected a number but got 'prashant'
Field 'id' expected a number but got 'prashant'

Time:09-28

I'm trying to get value of user field from my employee model but it's showing above error.I would request your solution to this problem.I have mentioned my models.py & views.py for reference.

models.py

class Employee(models.Model):
    First_Name = models.CharField(max_length=200,blank=False,null=False)
    Last_Name = models.CharField(max_length=200)
    DOB = models.DateField()
    Primary_skill=models.TextField(max_length=1000)
    user = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=True)
    Employee_Id = 
models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False,unique=True)


views.py 

def loginp(request):

    page ='login'

    if request.method=="POST":
        username = request.POST.get("Username")
        password = request.POST.get("Password")

        name = Employee.objects.get(user=username)
        context={'use':name}


        try:
            username = Employee.objects.get(username=1)

        except:
            messages.error(request,"Invalid Username")

        user = authenticate(request,username=username,password=password)

        if user is not None:
            login(request,user)
            return render(request,'profile.html',context)
        else:
            messages.error(request,"Authentication Failed.Please Try again with correct 
credentials")
    context={'page':page}
    return render(request,'login.html',context)

CodePudding user response:

any relationship by default have id in django but you can access another field using double underscore like (user__username,user__firstname,user__email) etc.

in you case you tried filter user by username but by default User field of Employee model have id so you got an error "Field 'id' expected a number but got 'prashant'"

put like this...

name = Employee.objects.get(user__username=username)

insted of...

name = Employee.objects.get(user=username)

CodePudding user response:

Why taking instance from Employee table?

Instead of this:

    name = Employee.objects.get(user=username)

Try this:

    name = User.objects.get(username=username)

And in your try block you are accessing Employee table with the field username , and there is no such field in it so it always goes to except block.

There instead of this:

    username = Employee.objects.get(username=1)

Try this:

    username = User.objects.get(username=1)

And if your purpose includes if user is included in the Employee table, You can try this way too:

    name = Employee.objects.get(user__username=username)

CodePudding user response:

name = Employee.objects.get(user=username)

here user is foreignkey. it should be int value(ID) if you want to filter with name then this will work

name = Employee.objects.get(user__username=username)

But making query in auth_user will be much better.

  • Related