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

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

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

<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

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

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

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

Side note:

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.)

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

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

VIEWS INDEX

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

Thank you, I’ve corrected this

The problem is here -

In your LikesPost model you have:

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:

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

I saw ‘username’ as a field to User object in django.contrib.auth | Django documentation | Django, 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

user = request.user

UPDATED VIEW

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"))

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

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.

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

[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

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.

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