Django开发中出现Field 'tag_number' expected a number but got 'КР-02211'错误的原因咨询
Hey there, let's break down this error clearly:
The root issue is a mismatch between your field's data type and the value you're trying to save to it:
- In your
models.py,tag_numberis defined as aPositiveIntegerField—this field type only accepts whole numeric values (no letters, hyphens, or other non-numeric characters). - But in your
BookUpdateView'sform_validmethod, you're settingself.object.tag_number = self.object.generate_tag(), and thegenerate_tag()method is returningКР-02211—a string with letters, a hyphen, and numbers, not a pure integer.
Django throws this error because it can't store a non-numeric string in a field designed exclusively for numbers.
How to Fix This
You have two solid options depending on what your tag_number is supposed to represent:
Option 1: Update the Field to Accept String Tags
If your tags are meant to include non-numeric characters (like the КР- prefix and hyphen), switch the field type to CharField (which handles text strings):
# models.py tag_number = models.CharField( 'Tag number', max_length=20, # Adjust this to match the longest possible tag length # You may need to replace numeric validators with ones that check your tag's string format )
Don't forget to create and run a database migration after changing the field type—Django needs to update the database schema to match.
Option 2: Modify generate_tag() to Return an Integer
If tag_number should strictly be a numeric value, fix your generate_tag() method to output only an integer. For example, if you want to keep the prefix logic but store just the numeric portion:
# Inside your Book model def generate_tag(self): # Replace this with your actual tag generation logic full_tag = "КР-02211" # Extract the numeric part after the hyphen and convert to integer return int(full_tag.split('-')[-1])
Quick Debug Tip
To confirm exactly what generate_tag() is returning, add a quick print statement to your view temporarily:
def form_valid(self, form): self.object = form.save(commit=False) generated_tag = self.object.generate_tag() print(f"Generated tag: {generated_tag}, Type: {type(generated_tag)}") # Shows value and data type self.object.tag_number = generated_tag self.object.save() return super().form_valid(form)
内容的提问来源于stack exchange,提问作者Ken Ist

