Django新手求助:出现invalid literal for int() with base 10: 'N/A'报错
Hey there! Let's break down this error and get your Django app running smoothly with MySQL.
What's Causing This Error?
The message invalid literal for int() with base 10: 'N/A' means Django tried to convert the string 'N/A' into an integer—and failed. Looking at your model code, the most likely culprit is your submitter ForeignKey field:
- ForeignKeys in Django store the integer primary key of the related model (in this case,
User). When you pass'N/A'to this field instead of a validUserinstance or integer ID, Django throws this mismatch error.
Step-by-Step Fixes
1. Track Down Where 'N/A' Is Being Passed
First, find the source of the problematic 'N/A' value:
- If using a form: If your form has an option labeled "N/A" for the submitter, make sure its underlying value is
Noneor an empty string, not the literal'N/A'. For example, a dropdown's "N/A" option should have a value like""instead of"N/A". - If creating objects via code: If you have code like
Strain.objects.create(submitter='N/A', ...), replace'N/A'withNone(since your model allowsnull=Trueforsubmitter), or pass a validUserinstance (e.g.,submitter=User.objects.get(username='your_test_user')).
2. Handle External Data (If Importing)
If you're pulling data from a CSV or external source that uses 'N/A' for missing submitters, add a conversion step before saving:
# Example: Processing a CSV row import csv from .models import Strain, User with open('strains_data.csv', 'r') as f: reader = csv.DictReader(f) for row in reader: # Convert 'N/A' to None for the submitter field submitter_str = row['submitter'] submitter = None if submitter_str == 'N/A' else User.objects.get(id=int(submitter_str)) Strain.objects.create( strain_name=row['strain_name'], data_of_generation=row['data_of_generation'], submitter=submitter )
3. Use Django Forms Correctly
If you're using a Django ModelForm, leverage ModelChoiceField to avoid invalid values entirely. This field automatically handles selecting valid User instances, and you can set a friendly empty label:
from django import forms from .models import Strain class StrainForm(forms.ModelForm): class Meta: model = Strain fields = ['strain_name', 'data_of_generation', 'submitter'] # Customize the submitter field to show "N/A" as the empty option submitter = forms.ModelChoiceField( queryset=User.objects.all(), required=False, empty_label="N/A" # Displays "N/A" to users, submits None to the database )
Quick Recap
Never pass string values like 'N/A' to a ForeignKey field—use None (if allowed by your model) or a valid related object/ID. This keeps your data types consistent with what Django and MySQL expect.
内容的提问来源于stack exchange,提问作者Pen Gerald

