Django - relation "app_name_modelname" does not exist - django

I've deployed my application to DigitalOcean. Everything works fine except this situation. I've added new GeneralComplaintDocument model, made migration locally, pulled from Github last version of project on DigitalOcean's server, deleted all migration files, migrated again, but still getting this error:
relation "documents_app_generalcomplaintdocument" does not exist
LINE 1: INSERT INTO "documents_app_generalcomplaintdocument"
models.py:
class Document(models.Model):
created_date = models.DateTimeField(default=timezone.now)
added_by = CurrentUserField()
class GeneralComplaintDocument(Document):
complaint_reason = models.CharField(max_length=500)
result = models.CharField(max_length=500)
def __str__(self):
return self.complaint_reason
P.S: everything works fine on local server.

I would suggest for do something like this:
first delete all migrations files in your app(documents_app)and next execute the below SQL query in your Database. Here we assume your app_name is documents_app.
delete FROM "django_migrations" WHERE "app" = 'documents_app';
then migrate ,
python manage.py makemigrations documents_app
python manage.py migrate documents_app

Related

Adding columns to an existing django table with a . postgreSQL db

I've been searching around for how to do this an di think i broke my table
I tried adding
dealership = models.ForeignKey('Employee', null=True)
To the field to the models.py, since I noticed thats where my other column fields were, and now the entire table is gone.
After some more research I saw that its supposed to be added to the migrations location and then run
$ python models.py migrations
Heres the model I want to add it to
## Gate access log - receives from RPi via API
##
class Eventlog(models.Model):
ENTRY = 1
EXIT = 2
EVENT_CHOICES = (
(ENTRY, 'Entry'),
(EXIT, 'Exit'),
)
event = models.PositiveSmallIntegerField(choices=EVENT_CHOICES)
employee = models.ForeignKey('Employee', null=True)
timestamp = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True, help_text="Whether the employee was granted access")
def __unicode__(self):
return self.timestamp
def __str__(self):
return self.timestamp
and as the comment suggests, it pulls the from a raspberry pi through an api
My question is how do I properly add the column, the db already has the information for the column data I can't imagine it's that difficult to simply pull that info and how do I get my table back? The table seems to have vanished after I added to the models.py manually and when I tried undoing it just never came back.
You need to run two commands:
python manage.py makemigrations
then
python manage.py migrate
To add columns in postgresql db solution as below:
pip install django-extensions
and add this in the install app of settings.py
INSTALLED_APPS = [
'django_extensions'
]
Now, run migrations for your installed apps
python manage.py makemigrations your_app_name
python manage.py migrtate your_app_name
Done! See Your Database...

NOT NULL constraint failed when running `migrate`

I changed my models.py file and when running migrate I get this error. The property is a OneToOneField(). I have tried adding null=True but that doesn't seem to fix it. It is also weird that even when I comment out the property and run makemigrations followed by migrate, I still get that exact same error. Is there a way to fix this? My model looks like this:
class Estimator(Employee):
avg_estimate = models.IntegerField()
class Job(models.Model):
created = models.DateTimeField(auto_now_add=True)
estimator = models.OneToOneField(Estimator, null=True)
address = models.CharField(max_length=100)
completed = models.BooleanField(default=False)
My guess is that you have created a migration without null=True, that won't migrate, then you created a second migration with null=True.
Running "migrate" will run both migrations in order, so the first one will fail again.
Assuming this is the case, then
1: delete the two most recent files in your migrations folder. (Open them first to confirm that they are creating the migrations as I described before deleting them).
2: run makemigrations again, with null=True in your models.py
This should create the equivalent of the second migration file, without the failing intermediate migration.

django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug

I'm learning Django from Tango with Django but I keep getting this error when I type:
python manage.py makemigrations rango
python manage.py migrate
This is the output:
django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug
Models.py:
from django.db import models
from django.template.defaultfilters import slugify
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.title
The reason for this constrain could be that you didn't have any field called slug in Category class when you have initially migrated it (First Migration), and after adding this field in the model, when you ran makemigrations, you have set default value to something static value(i.e None or '' etc), and which broke the unique constrain for the Category's table's slug column in which slug should be unique but it isn't because all the entry will get that default value.
To solve this, you can either drop the database and migration files and re-run makemigrations and migrate or set a unique default value like this:
slug = models.SlugField(unique=True, default=uuid.uuid1)
Edit:
According to Migrations that add unique fields, modify your migration file to overcome unique constrain. For example, modify your migration file (which added the slug field to the model) like this:
import uuid
from app.models import Category # where app == tango_app_name
class Migration(migrations.Migration):
dependencies = [
('yourproject', '0003_remove_category_slug'),
]
def gen_uuid(apps, schema_editor):
for row in Category.objects.all():
row.slug = uuid.uuid4()
row.save()
operations = [
migrations.AddField(
model_name='category',
name='slug',
field=models.SlugField(default=uuid.uuid4),
preserve_default=True,
),
migrations.RunPython(gen_uuid),
migrations.AlterField(
model_name='category',
name='slug',
field=models.SlugField(default=uuid.uuid4, unique=True),
),
]
I got a field with attribute unique, which was not unique [eg 2-time same value]
python3 manage.py migrate --fake
then
python3 manage.py makemigrations
python3 manage.py migrate
this did the trick
This means a slug should be unique. You may have some data in your model. You need to delete all the data in that model and you need to migrate again.
In this situation, you have two ways to fix the error;
You need to delete it from the Django admin site. More often than not, it may give an error when you are trying to open the model.
Open command prompt
move to project -> py manage.py shell -> from yourappname.models import modelname -> modelname.objects.delete()
Here if you define a product manager for your model. Then you have to define a delete function. Later you should makemigrate, migrate and continue with the second way
I just met this simiilar error: Django UNIQUE constraint failed. I tried examine the code for very long time, but didn't solve it. I finally used SQLiteStudio to examine the data, and found the data is problematic: I unintentionally added two SAME instances which violates the UNIQUE constraint. To be frank I haven't thought the error could be this naive and simple, and because so it took me a lot of time to find out!
I had the same problem and tried all the suggested answers. What finally worked for me was, after I defined the slug field as a URL in models, and ran the makemigrations. I edited the file in makemigrations adding a random number at the end of a basic URL, like this
Generated by Django 3.2.3 on 2022-02-02 20:58
from django.db import migrations, models
from random import randint
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_remove_post_slug1'),
]
operations = [
migrations.AddField(
model_name='post',
name='slug',
field=models.URLField(blank=True, default='http:/salpimientapa.com/' + str(randint(100000,999999))),
),
]
After I ran
python manage.py migrate
I edit the slug as a SlugModel and ran the makemigrations and migrate again
What worked for me was going to the admin and changing the value of duplicate slug, before running the migrations again.
Just delete the last migration in the migration folder
Then run
python manage.py makemigrations
python manage.py migrate
I faced the same issue and solved by populating my slugfied thro' the admin with unique values and without leaving any of them blank.
Basically: You add the field without unique=true in one operation, make a data migration that generates the correct shortuuids for you, and then change the field too unique again.
i have this error too ,
i did delete my database in djangoProject ( for example db.sqlite3 )
and then run
python manage.py makemigrations
python manage.py migrate
It's an Integrity Error probably because the migration will temper with the already exiting data in the database.
I had this error and here's what I did:
Enter in the project folder directory
Open the python interpreter
py manage.py shell
Import your Models
from yourappname.models import model
Delete existing data records in the model
model.objects.all().delete()
Exit the Python Interpreter
exit()
.
Another thing you could do is to set unique="false" on the affecting field. I think this should work; not so sure.

django 1.7 makemigrations on existed table

I want to use Django 1.7 for a new project.
and I already have database with many records.
In many Django tutorials,
it demo how to use migration system from a fresh new project.
In my case, use django-admin startapp todo
and will use a existed table named notesnote.
I use inspectdb to dump notesnote class and write it into todo/models.py
class NotesNote(models.Model):
title = models.CharField(max_length=100)
text = models.TextField()
pub_date = models.DateTimeField()
authors = models.CharField(max_length=10)
and then
python manage.py makemigrations todo
to generate todo/migrations/0001_initial.py
then
python manage.py migrate --fake todo
do a fake migrate(cause the table already existed).
Then, If I want to amend the table's field, say add a "category" field
category = models.CharField(max_length=30)
Then generate the 0002 migration diff by:
python manage.py makemigrations todo
However, when I do the migrate by
python manage.py migrate todo
I got error as below:
django.db.utils.OperationalError: no such table: todo_notesnote
Seems it add the app's name in front of the existed table.
Which steps should I do to make a usable migrations for existed table?
The documentation about integrating Django with a legacy database contains some useful advices for your use case: in particular you should add a db_table = 'notesnote' option to the inner Meta class of your model.

Migrations in Django 1.7

I am currently involved in a project where I am using Django 1.7 development version.I want to propogate changes that I make in my models (adding a field, deleting a model, etc.) into the database schema using "makemigrations" and "migrate" commmands.I added a "age" field to one of the models in my application.
country = models.CharField(max_length=50, blank=True)
address = models.CharField(max_length=100, blank=True)
postal_code = models.IntegerField(max_length=50, blank=True)
city = models.CharField(max_length=50, blank=True)
phone_no = models.CharField(max_length=25, blank=True)
skype_name = models.CharField('Skype Username',max_length=50, blank=True)
age=models.IntegerField(max_length=25,blank=True)
When I use "makemigrations" command ,the output is like---"No changes detected".I guess that "makemigrations" is not able to figure out the changes made to the schema.Any suggestions how can I make it work??
If you are adding initial migrations to an app, you must include the app name when using the makemigrations command.
python manage.py makemigrations your_app_label
If it is the first time you are migrating that app you have to use:
manage.py makemigrations myappname
Once you do that you can do:
manage.py migrate
If you had your app in database, modified its model and its not updating the changes on makemigrations you probably havent migrated it yet.
Change your model back to its original form, run the first command (with the app name) and migrate...it will fake it. Once you do that put back the changes on your model, run makemigrations and migrate again and it should work.
I have sometimes the same problem.
I manage to populate the change in the database by following :
rm -rf your_app/migrations/*
python manage.py migrate
if it doesn't work, consider a manual drop table before, if you don't have data in it.
it worked for me with django 1.7c1