Home > OS >  TypeError at / Field 'id' expected a number but got <username>
TypeError at / Field 'id' expected a number but got <username>

Time:12-02

returns username instead of user.id,i'm try to getting user.id in user_id field but getting username, the user-id field registerd as forignkey fiels of user,so it returns number only views.py


def index(request):
    if request.user.is_authenticated:
        cus = User.objects.get(pk=request.user.id)
        print(cus)
        if request.method == 'POST':
            task = request.POST['task']
            priority = request.POST['priority']
            date = request.POST['date']
            time = request.POST['time']

            add_task = AddTodo(task=task, priority=priority, date=date, time=time, user_id=cus)
            add_task.save()

            if add_task is not None:
                print("task added suuccesfuly", task)
            else:
                print("task not added", task)
    return render(request, 'index.html')

models.py

class AddTodo(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    task = models.CharField(max_length=100, blank=True)
    priority = models.IntegerField()
    date = models.DateField()
    time = models.TimeField()
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

exception:

TypeError: Field 'id' expected a number but got <User: captainamerica123>.

CodePudding user response:

You passed user object to user_id when you create AddToDo object. If you want to create with user_id, you have to pass user id not user object. Of course you can create with user object. So, you can update code as following

add_task = AddTodo(task=task, priority=priority, date=date, time=time, user_id=cus.id)

or

add_task = AddTodo(task=task, priority=priority, date=date, time=time, user=cus)

Both will work.

CodePudding user response:

def index(request):
    if request.user.is_authenticated:
        cus = User.objects.get(pk=request.user.id)
        print(cus)
        if request.method == 'POST':
            task = request.POST['task']
            priority = request.POST['priority']
            date = request.POST['date']
            time = request.POST['time']

            add_task = AddTodo(task=task, priority=priority, date=date, time=time, user_id=cus.id)
            add_task.save()

            if add_task is not None:
                print("task added suuccesfuly", task)
            else:
                print("task not added", task)
    return render(request, 'index.html')
  • Related