# ValueError: Field 'id' expected a number but got ''.

**URL:** <https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076>\
**Category:** Templates & Frontend\
**Created:** [January 8, 2023, 6:21pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076 "2023-01-08T18:21:43Z")\
**Posts on this page:** 11\
**Page:** 1

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [January 8, 2023, 6:21pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/1 "2023-01-08T18:21:44Z")

</div>

I’m trying to create a like/unlike button but this error keeps showing after several attempts at tweaking this

> # ValueError at /update\_like
> 
> Field ‘id’ expected a number but got ‘’.

VIEWS.PY

```auto
def update_like(request):
    username = request.user.username
    post_id = request.GET.get('post_id')
    post = NewTweet.objects.get(id = post_id)

    like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first

    if like_filter == None:
        new_like = LikesPost.objects.create(post_id=post_id, username=username)
        new_like.save()
        post.save()
        return HttpResponseRedirect(reverse("index"))
    else:
        like_filter.delete()
        post.save()
        return HttpResponseRedirect(reverse("index"))

```

INDEX.HTML

```auto
<div class="tweet-feed">
  {% for post in all_post%}
  <div class="tweet">
  <img src="http://placeimg.com/140/140/people" alt="author profile picture" class="tweet-author-image"/>
 <div class="tweet-feed-content">
 <div class="tweet-header">
 <a href="#" class="tweet-author-username">{{post.user}}</a>
 <div class="tweet-author-handle">@ {{post.user}</div>
 <div class="tweet-dot">.</div>
 <div class="tweeted-time">{{post.created_at}}</div>
   </div>
   <div class="tweet-content">
   <div class="tweet-created-content">{{post.caption}}</div>
   </div>
  <span id="likeCount"></span>
 <div class="engagement-icons">
  <ul class="engagement-icons-ul mt-1">
     <li><i class="fa-regular fa-comment"></i></li>
      <li><i class="fa-solid fa-retweet"></i></li>
      <li><a href="/update_like?post_id={{post.id}}"><i id="LikeBtn" class="fa-regular fa-heart"></i></a> 
      </li>
      <li><i class="fa-solid fa-arrow-up-from-bracket"></i></li>
    </ul>
                                    </div>
                                </div>
                            </div>
                        {% endfor %}

```

MODELS.PY

```auto
class User(AbstractUser):
    pass

class NewTweet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    caption = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__ (self):
        return f"{self.user} posted {self.caption}"

class LikesPost(models.Model):
    post_id = models.CharField(max_length=100)
    username = models.ForeignKey(User, on_delete=models.CASCADE, )

    def __str__ (self):
        return self.username

```

URLS.PY  
path(“update\_like”, views.update\_like, name=“update\_like”),

TRACEBACK

```auto
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\ __init__.py", line 1822, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\USER\Desktop\CS50\project4\network\views.py", line 131, in update_like
    like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 974, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 992, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 999, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1375, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1396, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1329, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1180, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\lookups.py", line 22, in __init__
    self.rhs = self.get_prep_lookup()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\related_lookups.py", line 120, in get_prep_lookup
    self.rhs = target_field.get_prep_value(self.rhs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\fields\ __init__.py", line 1824, in get_prep_value
    raise e. __class__ (
ValueError: Field 'id' expected a number but got ''.
[08/Jan/2023 19:20:02] "GET /update_like?post_id=4 HTTP/1.1" 500 122943

```

From the research I’ve done, I suspect the issue is coming from Models - username = models.ForeignKey(User, on\_delete=models.CASCADE) - but I don’t know how to rectify it

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 8, 2023, 6:35pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/2 "2023-01-08T18:35:23Z")

</div>

We need to see the view that is rendering the `index.html` template.

Side note:

> [@Theresa-o](#):
>
> `{% for post in all_post%}`

You’re missing the space between `all_post` and `%`. (I’m not sure this is causing any problem here, but in general, you want to ensure that your spacing is correct in Django templates - it can be very picky in that regards.)

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 8, 2023, 6:54pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/3 "2023-01-08T18:54:28Z")

</div>

Another side note not directly related to the issue at hand:

> [@Theresa-o](#):
>
> `like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first`

You’re missing the parens on the `first` function. (This may be a copy/paste error.)

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [January 8, 2023, 7:00pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/4 "2023-01-08T19:00:28Z")

</div>

VIEWS INDEX

```auto
def index(request):
    all_post = NewTweet.objects.all()
    context = {
        "all_post": all_post,
    }
    return render(request, "network/index.html", context)

```

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [January 8, 2023, 7:00pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/5 "2023-01-08T19:00:58Z")

</div>

Thank you, I’ve corrected this

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 8, 2023, 7:19pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/6 "2023-01-08T19:19:02Z")

</div>

The problem is here -

> [@Theresa-o](#):
>
> ```auto
> like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first
> 
> ```

In your `LikesPost` model you have:

> [@Theresa-o](#):
>
> ```auto
> username = models.ForeignKey(User, on_delete=models.CASCADE, )
> 
> ```

This means that your usage of `username` here is actually a reference to a `User` object and _not_ the User username field. But you’re defining that parameter as being:

> [@Theresa-o](#):
>
> ` username = request.user.username`

Which is a reference to the username field and not the User object.

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [January 8, 2023, 7:43pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/7 "2023-01-08T19:43:04Z")

</div>

> [@Theresa-o](#):
>
> username = request.user.username

I saw ‘username’ as a field to User object in [django.contrib.auth | Django documentation | Django](https://docs.djangoproject.com/en/4.1/ref/contrib/auth/), I thought that this can be referenced since I am using the default Django user model however I updated my code to but still receiving the same error

```auto
user = request.user

```

UPDATED VIEW

```auto
def update_like(request):
    username = request.user
    post_id = request.GET.get('post_id')
    post = NewTweet.objects.get(id = post_id)

    like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first()

    if like_filter == None:
        new_like = LikesPost.objects.create(post_id=post_id, username=username)
        new_like.save()
        post.save()
        return HttpResponseRedirect(reverse("index"))
    else:
        like_filter.delete()
        post.save()
        return HttpResponseRedirect(reverse("index"))

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 8, 2023, 7:49pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/8 "2023-01-08T19:49:05Z")

</div>

> [@Theresa-o](#):
>
> `user = request.user`

Yes, you updated the reference here, but you didn’t update this:

> [@Theresa-o](#):
>
> ` like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first()`

So that you’re passing `user` as the parameter in the filter.

Oh, I see, you are using `username` in the view - I missed that at first pass.

Please repost the complete traceback that you are getting with this revised version.

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [January 8, 2023, 7:57pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/9 "2023-01-08T19:57:13Z")

</div>

> [@KenWhitesell](#):
>
> Oh, I see, you are using `username` in the view - I missed that at first pass.
> 
> Please repost the complete traceback that you are getting with this revised version.

```auto
def update_like(request):
    username = request.user
    post_id = request.GET.get('post_id')
    post = NewTweet.objects.get(id = post_id)

    like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first()

    if like_filter == None:
        new_like = LikesPost.objects.create(post_id=post_id, username=username)
        new_like.save()
        post.save()
        return HttpResponseRedirect(reverse("index"))
    else:
        like_filter.delete()
        post.save()
        return HttpResponseRedirect(reverse("index"))

```

I’m getting this error even though I am logged in via Admin

# TypeError at /update\_like

‘AnonymousUser’ object is not iterable

TRACEBACK

```auto
[08/Jan/2023 20:55:31] "GET /update_like?post_id=4 HTTP/1.1" 500 109540
Internal Server Error: /update_like
Traceback (most recent call last):
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\USER\Desktop\CS50\project4\network\views.py", line 131, in update_like
    like_filter = LikesPost.objects.filter(post_id=post_id, username=username).first()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 974, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 992, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\query.py", line 999, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1375, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1396, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1302, in build_filter
    self.check_related_objects(join_info.final_field, value, join_info.opts)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\models\sql\query.py", line 1136, in check_related_objects
    for v in value:
  File "C:\Users\USER\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 249, in inner
    return func(self._wrapped, *args)
TypeError: 'AnonymousUser' object is not iterable
[08/Jan/2023 20:55:35] "GET /update_like?post_id=4 HTTP/1.1" 500 109540
type or paste code here

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [January 8, 2023, 8:14pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/10 "2023-01-08T20:14:08Z")

</div>

This could be _many_ things. You could have mistakes in your configuration regarding user authentication, or not having your session or cookies configured correctly, or any of a number of different things. Or that browser session that you are using here might not be logged in like you think it is.

Do you have any other views working that use `request.user` to get the user currently logged in? Clearly, `user` is being set on the `request` object - otherwise you’d be getting an attribute error on `request`. Instead, you’re getting AnonymousUser, so the middleware is working.

If I had to debug this, I’d create a trivial view that prints the request object, including request.user and request.GET. Then I’d use my browser’s developer tools to examine the cookies being set when logging in and verifying that the cookie is being returned when fetching this page. (I’d also try to fetch the page directly by the url and not going through the link.)

All this is just to try and gather information as to what might be wrong.

---

<div class="post-metadata">

**Author:** ![Theresa-o](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/theresa-o/32/7565_2.png) [@Theresa-o](https://forum.djangoproject.com/u/Theresa-o)\
**Post date:** [January 8, 2023, 8:27pm UTC](https://forum.djangoproject.com/t/valueerror-field-id-expected-a-number-but-got/18076/11 "2023-01-08T20:27:37Z")

</div>

Thank you for assisting, I cleared my cached and refreshed and this is working now.
