ValueError: invalid literal for int() with base 10: '' | Django - python

I'm using Django to build an ecommerce webapp. I wrote this code in models.py
from django.db import models
# Create your models here.
class Product(models.Model):
product_id = models.AutoField
product_name = models.CharField(max_length=50)
category = models.CharField(max_length=50, default="")
subcategory = models.CharField(max_length=50, default="")
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300)
pub_date = models.DateField()
image = models.ImageField(upload_to='mainShop/images', default="")
Then, I performed makemigrations using
python manage.py makemigrations
which produced the following
D:\Projects\PyCharm Projects\VeroniCart\home>python manage.py makemigrations
No changes detected
Then I did
python manage.py migrate
This gave me the error:
ValueError: invalid literal for int() with base 10: ''
I'm also attaching a log file with the complete error.
Any help appreciated!

Issue solved. All I did was I deleted all files from my app's migrations directory (except migrations/init.py) and deleted the database file db.sqlite3 from the project directory.
Then I repeated the previous steps (makemigrations and migrate).
Django again created all migrations files and a new db.sqlite3 file, so this worked for me.

Related

Django: 0001_initial.py is not on current status after complementing models.py

I am new to Django/python and I am facing a problem with my models.py.
I added some attributes, saved it -> py manage.py makemigrations -> py manage.py migrate
but the current attributes are not shown in the 0001_initial.py.
Also when I am opening the database in my DB Browser for SQLite I still get the old status.
Here's my code:
models.py
from django.db import models
# from django.contrib.auth.models import User
# Create your models here.
category_choice = (
('Allgemein', 'Allgemein'),
('Erkältung', 'Erkältung'),
('Salben & Verbände', 'Salben & Verbände'),
)
class medicament(models.Model):
PZN = models.CharField(max_length=5, primary_key=True) # Maxlaenge auf 5 aendern
name = models.CharField('Medikament Name', max_length=100)
description = models.CharField('Medikament Beschreibung', max_length=500)
category = models.CharField(max_length=100, blank=True, null=True, choices=category_choice)
instructionsForUse = models.CharField('Medikament Einnehmhinweise', max_length=400)
productimage = models.ImageField(null=True, blank=True, upload_to="images/")
stock = models.PositiveIntegerField(default='0')
reorder_level = models.IntegerField(default='0', blank=True, null=True)
price= models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
sold_amount = models.IntegerField(default='0', blank=True, null=True)
sales_volume = models.DecimalField(default='0.0', max_digits=10, decimal_places=2)
def __str__(self):
return self.name
And the 0001_initial.py
# Generated by Django 3.2.16 on 2023-01-05 14:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='medicament',
fields=[
('PZN', models.CharField(max_length=5, primary_key=True, serialize=False)),
('name', models.CharField(max_length=100, verbose_name='Medikament Name')),
('description', models.CharField(max_length=500, verbose_name='Medikament Beschreibung')),
('category', models.CharField(default='Allgemein', max_length=100)),
('instructionsForUse', models.CharField(max_length=400, verbose_name='Medikament Einnehmhinweise')),
('productimage', models.ImageField(blank=True, null=True, upload_to='images/')),
('stock', models.IntegerField(default='0')),
],
),
]
First a basic explanation and below an answer to your specific situation
There is 2 steps:
"makemigrations" scans your code, finds changes in models an will create migrations files according to changes like
001_initial.py
002_auto_xyz.....py
There is an initial file and then subsequent migration files having a running number and depend on each other which you can see in the file e.g.
dependencies = [
('users', '0003_auto_20210223_1655'),
]
Once a migration file is created it will not change anymore and all later modifications in the code will be reflected in new additional migrations file after a new makemigration is executed.
"migrate" will take the created migration files, will check your database which migrations have been applied already to this specific database(!) and apply the once that are pending. In the database there is a table created that stores info about the already applied migrations.
That means for example you can run a migrate on a database on your development server and independent from that run migrate on a database on your production server. Both migrate commands will read the existing migration files and perform migrations in the database.
So if you made an initial model -> makemigrations -> migrate, you will see an 001_initial.py migrations file.
If you make changes to the models -> makemigrations again -> migrate again you should find only the changes in the 002_... migrations file and find also the changes in your database.
In any Django project, you only run makemigrations once (at the first initialization of your models), after that you run ONLY migrate for any updates.
As for your problems, you should delete your SQLite DB, and also delete all migrations files that end with .pyc.
After that run makemigrations then migrate, (and don't run makemigrations again, the reason being that it will cause problems and collisions with older SQL migrations based on the previous makemigrations).

Error: no such table when extending Abstract User Model

I wanted to extend the Base Abstract User Model within Django to have some other Fields:
class Student(AbstractUser):
birth = models.DateField(default=datetime.date.today)
street = models.CharField(max_length=20)
street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)])
city = models.CharField(max_length=20)
province = models.CharField(max_length=20)
code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))])
address = str(street) + str(street_number) + str(city) + str(code) + str(province)
def __str__(self):
return f'Adresse: {self.address}'
I added this into my settings.py file:
AUTH_USER_MODEL = 'mainApp.Student'
But I get an Error saying there is no such table "Student" when trying to load /admin/.
I have made all the migrations using:
python manage.py makemigrations mainApp
python manage.py migrate mainApp
Error:
OperationalError at /admin/
no such table: mainApp_student
If y'all need any more infos, please comment!
Try in first time to run:
python manage.py makemigrations
python manage.py migrate
Without put the app name to migration process
You cannot define "address" like this. Database column is not for string concatenation of other columns, nor any calculation. It can cause error.

How to update Django model max_length value in database after tables have already been migrated

I need more characters available for the title and subtitle fields of a blog I made. I would like to increase the max_length from 100 to 150. Here is the table:
class Post(models.Model):
title = models.CharField(max_length=100)
subtitle = models.CharField(max_length=100)
slug = models.SlugField(max_length=99)
date_added = models.DateTimeField(default=timezone.now)
author = models.CharField(max_length=60)
body = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
tags = models.ManyToManyField(Tag)
Through another Q&A I took the advice to change the max_length in the model (in my case from 100 to 150) and type this in the command prompt:
python manage.py makemigrations
python manage.py migrate
I then committed the changes and it allowed me to type more characters in but when I submitted the post it came up with a database error saying the fields can only take 100 characters.
How can I get the database to recognize the change in max_characters?
You can change it and re run the migrations again or do python manage.py migrate my_app 0008_previous_migration you can then delete the newer migration file with the error in it and re run the commands.
You can do python manage.py showmigrations my_app

difficulty in updating csv file

I tried to update the CSV file with a description column. I tried to add an update to the model by adding description = models.CharField(max_length=200, default='SOME STRING') like this:
wine = models.ForeignKey(Wine)
pub_date = models.DateTimeField('date published')
user_name = models.CharField(max_length=100)
comment = models.CharField(max_length=200)
rating = models.IntegerField(choices=RATING_CHOICES)
description = models.CharField(max_length=200, default='SOME STRING')
When I run migrate for this change I get the following error:
c:\Users\Amira Joshi\Desktop\winerama>python manage.py makemigrations
Migrations for 'reviews':
reviews\migrations\0002_review_description.py
- Add field description to review
How can I solve it? Please help!
This is not an error:
c:\Users\Amira Joshi\Desktop\winerama>python manage.py makemigrations
Migrations for 'reviews': reviews\migrations\0002_review_description.py
- Add field description to review
With this django says that the migration file is created, now you must apply the migration by running this command:
python manage.py migrate

Django 1.9 CharField length modifications are not applied

I'm using django 1.9 and the admin site for cataloging.
I changed this in my models.py:
localidad = models.CharField(max_length=30, verbose_name='Localidad')
for this:
localidad = models.CharField(max_length=300, verbose_name='Localidad')
I saved models.py and made manage.py makemigrations and migrate but changes are not reflected, an error shows up saying the field has 30 character max.
Any help any help would be appreciated

Categories

Resources