I'm working on creating a filter in django where the options displayed are coming from a new column in the database. It turns out that this column was created directly in the database and so that it could be displayed in my template, I need to capture this field in the models.
After some research, I found in django's own documentation a function called "inspectdb" that is called by manage.py. So far so good, after executing the function, the database fields are added to my project so that they can be directed to their corresponding app.models.
The documentation indicates that I must perform a python manage.py migrate for the sync to complete, this snippet of code is where the problem happens. When performing the migrate, I get the following error: "django.db.utils.ProgrammingError: relation "crontabmanager" already exists"
The "crontabmanager" table actually exists in my database, but it is not changing at this time.
Some actions were taken to try to get around this problem, for example:
I tried to ignore the migration and use the new field directly in the system, but it returns stating that the new column does not exist
Delete the migration file and create a new "makemigration"
Delete the "crontabmanager" table from the database for django to recreate through the ORM
Changing models.py properties to ignore changes made
Below is the snippet of my current models.py code:
from django.db import models
class Crontab(models.Model):
client = models.TextField('Cliente', blank=True, null=True)
script = models.TextField('Nome do script', primary_key=True)
schedule_code = models.TextField('Codigo Crontab', blank=True, null=True)
crontab_command = models.TextField("Comando", blank=True, null=True)
log = models.TextField("Log", blank=True, null=True)
class Meta:
verbose_name = 'Crontab'
verbose_name_plural = 'Crontab'
db_table = "crontabmanager"
class Trello(models.Model):
id_card = models.TextField('ID do Card', primary_key=True)
card_name = models.TextField('Nome do Card', blank=True, null=True)
due_date = models.TextField('Data de conclusão', blank=True, null=True)
list_name = models.TextField('Nome da lista', blank=True, null=True)
tipo_corte = models.TextField('Tipo do corte', blank=True, null=True)
cortes = models.TextField('Numero de cortes', blank=True, null=True)
unidade = models.CharField(max_length=200, blank=True, null=True) #new field added
class Meta:
db_table = "trello_pta"
error when running python manage.py migrate
$ python3 manage.py migrate
Operations to perform:
Apply all migrations: accounts, admin, auth, contenttypes, core, sessions, users
Running migrations:
Applying core.0002_initial...Traceback (most recent call last):
File "/home/file_names/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 87, in _execute
return self.cursor.execute(sql)
psycopg2.errors.DuplicateTable: relation "crontabmanager" already exists
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
...
return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "crontabmanager" already exists
Related
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).
I am facing this problem in django where even though there is a Profile model in my models.py file which extends the django User model still on running the 'makemigration' and 'migrate' commands the Profile table is not being generated in database.
This is my models.py:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
clg_name = models.CharField(max_length=200)
class Student(models.Model):
name = models.CharField(max_length=100, blank=False)
enrollment_number = models.IntegerField(unique=True, null=True, blank=False)
clg_name = models.CharField(max_length=200, blank=False)
program_name = models.CharField(max_length=30, blank=False)
class Result(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
sem = models.IntegerField()
exam_name = models.CharField(max_length=30)
percnt = models.FloatField(null=True)
cgpa = models.FloatField(null=True)
class Marks(models.Model):
result = models.ForeignKey(Result, on_delete=models.CASCADE)
course_name = models.CharField(max_length=100, null=True)
course_code = models.IntegerField(null=True)
course_credit = models.IntegerField(null=True)
grade = models.FloatField(null=True)
Here is the output of py manage.py makemigration account:
Migrations for 'account':
account\migrations\0001_initial.py
- Create model Result
- Create model Profile
- Create model Marks
And this is the output of py manage.py migrate:
Operations to perform:
Apply all migrations: account, admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
I don't know what is wrong with your account app . but you can solve it with :
1- delete __pycache__ and migrations folders located inside account app
2 - run python manage.py makemigrations account zero
3 - then run python manage.py makemigrations account
4 - finally run python manage.py migrate
I solved the following error by just dropping the whole Database and deleting the py_cache and migration files of my application. Just create another database and rerun the migration and migrate commands. Hope this helps.
(New to Django) - I am looking to create two model with a foreign key. The first model is called Portfolio, and each Portfolio has many member through the second model Portfoliomember.
It currently looks like this:
class Portfolio(models.Model):
portfolio_name = models.CharField(max_length=30, blank=True, null=True)
def __str__(self):
return self.portfolio_name
class Meta:
db_table = "portfolio"
class PortfolioMember(models.Model):
portfolio = models.ForeignKey(Portfolio, related_name = "portfoliomember", on_delete=models.CASCADE)
quality = models.FloatField(blank=True, null=True)
def __str__(self):
return self.portfolio
class Meta:
db_table = "portfoliomember"
Later i aim at using formset in a form. but for now, when i try to create the migration, i get the following :
Running migrations:
Applying app.0019_auto_20210318_1544...Traceback (most recent call last):
File "C:\Users\FrankyDoul\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "portfoliomember" does not exist
django.db.utils.ProgrammingError: relation "portfoliomember" does not exist
Is there an obvious reason why this would not work ?
Why do you define in your Meta class db_table? I don't know what is your app name but normally you don't need to do that except for specific reason. See this (https://docs.djangoproject.com/en/3.1/ref/models/options/) " Django automatically derives the name of the database table from the name of your model class and the app that contains it".
So when you define db_table = 'another_name', you override the database table name. I would suggest to remove this line i.e. db_table = "portfoliomember" and see if the error persist.
I'm still learning to use Django and I have an issue while trying to create a model.
Here's my models.py
class Identifiants(models.Model):
id = models.AutoField(primary_key=True)
taxon = models.IntegerField(unique=True)
noms = models.TextField(blank=True, null=True)
fiche = models.IntegerField(blank=True, null=True)
comestible = models.TextField(blank=True, null=True)
sms = models.NullBooleanField()
a_imprimer = models.NullBooleanField()
lieu = models.TextField(blank=True, null=True)
apparition = models.TextField()
class Meta:
managed = True
db_table = 'identifiants'
The makemigrations command works with no issues but the migrate one is where I have problems
Running migrations:
Applying app.0001_initial...Traceback (most recent call last):
File "/usr/lib/python3.5/site-packages/django/db/backends/utils.py", line 83,
in _execute
return self.cursor.execute(sql)
psycopg2.DataError: NUMERIC precision 65535 must be between 1 and 1000
LINE 1: ...iants" ("id" serial NOT NULL PRIMARY KEY, "taxon" numeric(65...
I'm using IntegerField method so I can't see why there is an issue ...
Can anyone help me ?
Thanks
Remove id = models.AutoField(primary_key=True) id is automatically created by django.
check it here, its similar to your question.
While I save UserProfile into a database,
there's an error "UserProfile has no column named gender error".
Here's my models.py
""" UserProfile : user information """
class UserProfile(models.Model):
# User basic inherits : username, password, email
user = models.OneToOneField(User)
# Profile information
nickname = models.CharField(max_length=63, unique=True, null=False)
url = models.URLField(blank=True, null=True)
birth = models.DateField(null=True) # TODO change null = false
gender = models.CharField(max_length=15, null=False)
nation = models.CharField(max_length=63, null=True)
region = models.CharField(max_length=63, null=True)
description = models.TextField(blank=True, null=True)
# ImageField: http://goo.gl/ZQEG4e
avatar = models.ImageField(upload_to='/avatar/')
# Foreign Keys
tag = models.ManyToManyField(TagCloud)
and while I tested it from ./python models.py shell I typed
> from UserAndPlace.models import *
> u1 = User.objects.get(username="user1")
> u1.username
u'user1'
> p1 = UserProfile(user=u1, gender="female")
> p1.user.username
u'user1'
> p1.gender
u'female'
> p1.save()
OperationalError Traceback (most recent call last)
<ipython-input-9-e08e160cd285> in <module>()
----> 1 p1.save()
....
OperationalError: table UserAndPlace_userprofile has no column named gender
I did python manage.py syncdb and also check errors with python manage.py sql UserAndPlace
How can I fix this errors?
Thanks for your help in advance.
syncdb will not create or modify columns if they already exist in the database. If you already had the model and then you added the gender column, running syncdb will not do anything.
You need to drop the table and re-create it again. If you are using sqlite, simply delete the database file and run syncdb.
If you are using another database, run manage.py sqlclear yourapp and this will give you the SQL you need to execute to reset the tables for the app yourapp (make sure you replace yourapp with the name of the application that has the profile model).
Then, run syncdb again to recreate your models.
Have you done a python manage.py syncdb after you made any changes to your model? This error usually happens when the model and the database are out of sync.