Automatic ID field returning 'None' in Django

Issue

I’m a beginner in Django trying to create a program that will save a model with some input.

(Eventually, I’ll be using a form for that input but the request.POST would contain things I want to send to multiple different places so I can’t just use a ModelForm.)

This is the code for the model:

class Bid(models.Model):
    bid_owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="owner")
    bid_value = models.DecimalField(max_digits=6, decimal_places=2)
    bid_no = models.IntegerField(default=0, null = True, blank=True)
    bid_open = models.BooleanField(default=True, null = True, blank=True)
    bid_winner = models.ForeignKey(User, blank=True, default="None", null=True, on_delete=models.CASCADE, related_name="winner")

    def __str__(self):
        return f"My ID is {self.id} and this is {self.bid_owner}'s listing"

And this is the code I’m calling in views.py:

def bar(request):
    foo = Bid(bid_owner = request.user, bid_value = 25)
    foo.save()

But it keeps bringing up the error:

Field ‘id’ expected a number but got ‘None’.

From the documentation, I’ve seen the contents of the id field should automatically generate during saving so I’m at a loss on how to solve this.
In rendering an HttpResponse showing the contents of foo everything seems to be working except for the id. I can also create a new Bid just fine using admin.

This is the full traceback:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/createpage

Django Version: 3.2.7
Python Version: 3.9.7
Installed Applications:
['auctions',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value
    return int(value)

The above exception (invalid literal for int() with base 10: 'None') was the direct cause of the following exception:
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Casual Hermit\Documents\cs50_webdev\projects\project2\commerce\commerce\auctions\views.py", line 121, in creation_page
    foo.save()
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 763, in save_base
    updated = self._save_table(
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 868, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
    return manager._insert(
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1415, in execute_sql
    for sql, params in self.as_sql():
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1358, in as_sql
    value_rows = [
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1359, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1359, in <listcomp>
    [self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1300, in prepare_value
    value = field.get_db_prep_save(value, connection=self.connection)
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related.py", line 971, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 2486, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\Casual Hermit\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value
    raise e.__class__(

Exception Type: ValueError at /createpage
Exception Value: Field 'id' expected a number but got 'None'.

Solution

The problem is in default value in bid_winner field.

You are trying to create a Bid record without passing bid_winner. So when saving Bid object, Django tries to fill bid_winner column with its default value which is "None".

But Django expects to find an id in that because bid_winner is ForeignKey.

So omit default value of bid_winner to fix that. As you have declared null=True, it would be None if you don’t pass anything to it.

Answered By – Amin

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published