Getting this error when submitting a form > ValueError at /forms_testing/forms_testing/ Field 'id' expected a number but got 's'

This is something new.

I get this error when submitting form.

I have another form with one textfield that works fine.

Its this one that causes errors.

Field 'id' expected a number but got 's'. What does "s" mean? Where is it coming from?

What does it mean?

Is it because it is expecting an “id” but i’m sending a “slug” instead?

If so, how can i make it work by sending an “id” and at the same time make sure that the “slug” is displayed in the URL address?

I already tried fixing this by deleting migrations and making a new migration and tried it fresh and still not fixed.

views.py

def forms_testing(request):

    if request.method == 'POST':
        add_book_form = AddBookForm(request.POST)
        if add_book_form.is_valid():  
            add_book_form.save()
            return redirect('forms_testing:forms_testing')
    else:
        add_book_form = AddBookForm()
    return render(request,'forms_testing/forms_testing.html', {
            'add_book_form':add_book_form
        })


urls.py

    path('book/<slug:book>/', views.book, name='book'),

models.py

class Book(models.Model):
	title = models.CharField(max_length=300,blank=True)
	slug = models.SlugField(max_length=300,blank=True)
	author = models.ManyToManyField(User, null=True,blank=True)
	genre = models.ManyToManyField(Genres,  null=True, blank=True)
	edition = models.CharField(max_length=300,blank=True)
	format_type = models.CharField(max_length=300,blank=True)
	languages = models.ManyToManyField(Languages, max_length=300,blank=True)
	featured_image = models.ImageField(upload_to='media/FEATURED_IMAGES/',blank=True)
	description = RichTextField(max_length=30000,blank=True)
	published_date_re = models.DateTimeField(auto_now_add=False, blank=True)
	published_date_or = models.DateTimeField(auto_now_add=False, blank=True)
	publisher = models.ManyToManyField(Publisher,max_length=300,blank=True)
	isbn = models.CharField(max_length=100, blank=True)
	isbn_10 = models.CharField(max_length=100, blank=True)
	isbn_13 = models.CharField(max_length=100, blank=True)
	pages = models.CharField(max_length=300,blank=True)
	amazon_link = models.URLField(max_length=2000,null=True,blank=True)
	walmart_link = models.URLField(max_length=2000,null=True,blank=True)
	awards_prizes = models.ManyToManyField(AwardsPrizes,max_length=400,null=True,blank=True)
	

	def get_absolute_url(self):
		return reverse('forms_testing:book', args=[self.slug])

	def __str__(self):
		return self.title


is there anything out of place?

please help.

It’s always more helpful if you post the complete traceback.

We’re likely also going to need to see the AddBookForm, too.

Traceback:


Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/forms_testing/forms_testing/

Django Version: 4.1
Python Version: 3.9.10
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'django.contrib.sitemaps',
 'django_experiments_app.apps.DjangoExperimentsAppConfig',
 'formsets_app.apps.FormsetsAppConfig',
 'crypto.apps.CryptoConfig',
 'membership.apps.MembershipConfig',
 'meta',
 'forms_testing.apps.FormsTestingConfig',
 'django_filters',
 'treebeard',
 'ecommerce.apps.EcommerceConfig',
 'product_catalog.apps.ProductCatalogConfig',
 'big_data.apps.BigDataConfig',
 'django_comments_xtd',
 'django_comments',
 'blog.apps.BlogConfig',
 'ckeditor',
 'allauth',
 'allauth.account',
 'allauth.socialaccount',
 'allauth.socialaccount.providers.google',
 'allauth.socialaccount.providers.facebook',
 'allauth.socialaccount.providers.twitter',
 'allauth.socialaccount.providers.github']
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 "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 2018, in get_prep_value
    return int(value)

The above exception (invalid literal for int() with base 10: 's') was the direct cause of the following exception:
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/ariethan/Documents/django_apps/django_experiments/django_experiments/forms_testing/views.py", line 16, in forms_testing
    add_book_form.save()
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.9/site-packages/django/forms/models.py", line 549, in save
    self._save_m2m()
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.9/site-packages/django/forms/models.py", line 530, in _save_m2m
    f.save_form_data(self.instance, cleaned_data[f.name])
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.9/site-packages/django/db/models/fields/related.py", line 1966, in save_form_data
    getattr(instance, self.attname).set(data)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.9/site-packages/django/db/models/fields/related_descriptors.py", line 1167, in set
    else self.target_field.get_prep_value(obj)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.9/site-packages/django/db/models/fields/related.py", line 1152, in get_prep_value
    return self.target_field.get_prep_value(value)
  File "/Users/ariethan/Documents/django_apps/django_experiments/virt/lib/python3.9/site-packages/django/db/models/fields/__init__.py", line 2020, in get_prep_value
    raise e.__class__(

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


AddBookForm


class AddBookForm(ModelForm):  
	title = forms.CharField(widget=forms.TextInput(attrs={}))
	author = forms.Select()
	genre = forms.Select()
	edition = forms.CharField(widget=forms.TextInput(attrs={}))
	format_type = forms.Select()
	languages = forms.CharField(widget=forms.TextInput(attrs={}))
	featured_image = forms.ImageField()
	description = forms.Textarea()

	published_date_re = forms.DateField(widget=forms.SelectDateWidget())
	published_date_or = forms.DateField(widget=forms.SelectDateWidget())

	publisher = forms.Select()
	isbn = forms.CharField(widget=forms.TextInput(attrs={}))
	isbn_10 = forms.CharField(widget=forms.TextInput(attrs={}))
	isbn_13 = forms.CharField(widget=forms.TextInput(attrs={}))
	pages = forms.CharField(widget=forms.TextInput(attrs={}))

	class Meta:
		model = Book
		fields = [
			'title','edition','format_type','languages','description','published_date_re','published_date_or','isbn','isbn_10','isbn_13','pages','publisher','genre','author'
		]




thank you

The error is being thrown from this line of code - and the line after that in the traceback references _save_m2m - which means that you have some invalid data in one of your many-to-many form elements.
In this case, my guess is that in one (or more) of your Select boxes, you’re not returning the primary key as the value returned from the select box - instead you’re returning some text value.

Probably the easiest way to find which one would be to visually examine your select widgets being rendered and verify that the values are the primary keys of the tables involved in the M2M relationships. (You can display just about anything as the option label, but unless you’re manually going to query data in your view, the value being returned for a selection needs to be the PK of the object(s) being selected.)