I am learning Django and have created a table in Django using PyCharm. I entered some values in the table and after that, I added another column to the table. Now, when I attempted to makekigrations, it happened successfully but when I tried to migrate, a lot of errors appeared which mainly said that an Empty Column is being attached and so on.
After that I made a lot of tries, first by allowing Null values in that column then by commenting out the column but unsuccessfully.
Now, even if I maintain the same code in the models.py file, the same errors keep appearing.
Here is the code of models.py file:
from django.db import models
class Albums(models.Model):
# name = models.CharField(max_length=250, default=None)
artist = models.CharField(max_length=250)
duration = models.CharField(max_length=20)
# def __str__(self):
# return self.artist
class Songs(models.Model):
album = models.ForeignKey(Albums, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
PS: I have tried restarting PyCharm as well.
You needed to put null=True, blank=True in there before making migrations. Because you didn't do that, you now have a bad migration file and every time you make new migrations, you're just adding a file to the migrations folder, but the bad migration file still exists and is unapplied. You need to go into your migrations folder and delete the bad migration file that is causing errors. Once you do that, you should be able to migrate successfully.
Related
I am making a notes app. When I try to create a foreign key to link the user and its notes, im getting an error while using
python manage.py migrate
. I am very new to foreign keys, I looked at the Django docs, this is how they created a foreign key.
here's the code :
from django.db import models
class User(models.Model):
username = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
class Note(models.Model):
body = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.body[0:50]
here's the error :
django.db.utils.IntegrityError: NOT NULL constraint failed: new__api_note.author_id
Your issue is that that there are existing notes in the database that do not have a author_id field, but you have not set a default value and neither allowed to to be kept blank. Thus it's a IntegrityError to add the field.
You can solve this in 2 ways:
Allow the field to be blank
Delete the last migration in your migrations folder
Edit the author field like this:
author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
Run makemigrations and migrate
Set a default value for the field
Delete the last migration from the migrations folder. You can also edit it but simply deleting it is easiest
Run makemigrations again
During make migration, it will prompt you if you want to provide a default value for the field. Select "Provie a one of value for now"
Type models.User.objects.all().first() or alternatively some other "defalt" author for existing notes
Run migrate
You can also solve the problem by removing all existing notes from the database
I am moving from Rails to Django and have an existing database. I created models.py via python manage.py inspectdb > models.py, made changes, and tested some endpoints. Everything seems fine.
I then ran python manage.py makemigrations and migrate to make the initial django mirgation.
I noticed an old Rail's specific Model / table called ArInternalMetadata / ar_internal_metadata. I figure I could easily remove the table by simply removing the model from models.py and rerun makemigrations however when I do that, django just says No changes detected. Running migrate doesn't remove the table either.
Figured it out. When inspectdb creates Models from an existing database, it sets managed in the Meta inner class to False by default.
class AssetCategories(FacadeModel):
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
name = models.CharField(max_length=255)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'asset_categories'
Per the Django 2.1 Docs this will prevent deletion from happening
If False, no database table creation or deletion operations will be performed for this model
Removing managed = False from the Meta class allows makemigrations / migrate to delete the table.
This is a strange one. Maybe I missed it but I have search through all Django documentation and SF but could not find an answer for this. I have a table with about 30 columns. The table looks like this...
Class Customer (models.Model):
customer_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=35)
last_name = models.CharField(max_length=35)
middle_initial = models.CharField(max_length=2)
mail_addr1 = models.CharField(max_length=50)
mail_addr2 = models.CharField(max_length=50)
mail_city
mail_state
mail_zip
bill_addr1
bill_addr2
...
...
active_yn = models.ForeignKey('Status', models.DO_NOTHING) # <-- This one
...
...
home
mobile
The offending field is "active_yn". Django keeps spitting out an error saying that it is now a valid field.
Here's the things I am sure of:
The table definitely have this field in the correct DB, schema, table, etc
It is not the last field on the table.
inspectdb for this table is also missing this field.
I drop and re-add this column and it is still not showing.
The field is a TINYINT(3) - referencing a table Django recognized.
I am using MySQL
I have been trying to debug this for days now. Any ideas?
Thank you all for helping. I found the issue. The problem is on the DB side. I am using root user connecting directly to the DB. I have the settings file connecting with a different user with tables and fields granted to it. This table has this one field not in the grant to this user (Not my doing... urgh). Anyway, once I added this field, everything works as expected.
I appreciate all your help. Hopefully the next guy will find this useful.
Cheers!
I have 5 models in one of my apps
Report ReportData Customer ..etc
For some reason, ever since my last deployment, I can no longer change or create new Report or Customer objects, but everything else works? Any idea why this would be happening? The admin page just outputs nothing on the add link and the change link outputs nothing as well.
Django==1.9.1
I have tried restarting servers, running migrations, and restarting database. The development version works fine. Such a strange problem.
As you can see, there are no fields even though this object has been populated with tons of data in the database.
Here is my Report model:
class Report(models.Model):
public_uuid = models.UUIDField(max_length=256,default=util.make_uuid,unique=True)
customer = models.ForeignKey('Customer')
has_payed = models.BooleanField(default=False)
#... etc
Here is how I register items in the admin:
admin.site.register(Customer)
admin.site.register(Report)
admin.site.register(...etc)
The other 3 models I have work fine. The only difference between these two models and the other three (that work and are editable with the admin tool) is that these two models have #property and #staticmethod methods attached to them.
Just had this issue
When using auto_now_add=True or editable=False in the field definition, the admin will not show the corresponding fields unless you specify them in the readonly_fields of the admin form definition.
if in models.py
class TransmissionLog(models.Model):
dataSource = models.ForeignKey(Browser, editable=False)
dateCreated = models.DateTimeField(auto_now_add=True, editable=False)
then admin.py needs
class TransmissionAdminManager(admin.ModelAdmin):
readonly_fields = ['dataSource', 'dateCreated']
admin.site.register(TransmissionLog, TransmissionAdminManager)
A duplicate model field is giving me trouble (no such table appname_modelname when I run my webpage). Whenever I do ./manage.py migrate appname, it gives me "duplicate field". I checked my models.py, there is only one of them there. How do I delete that duplicate field? It seems no matter what I do, it stays. I've tried:
Deleting the database
Deleting migrations folder in app folder
Doing ./manage.py sqlclear south and then dropping the south_migrationhistory table in the dbshell
./manage.py schemamigration appname --initial, ./manage.py migrate appname --fake
I've run out of ideas.
class Document(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True, default=None)
identity = models.CharField(max_length=255, default=None, null=True)
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
docfile = models.FileField(upload_to=_upload_path, storage=fs) # upload_to is a path inside the storage path
def get_upload_path(self,filename):
return str(self.user.id) + '/' + str(date.today()) + '/' + filename
You can't do this, for your user foreign key, Django ORM will create a database field named user_id (your foreign key field name plus _id) to use it as a FK in the database.
You don't have to create this field yourself (the ORM will take care), even if you need it, change the name of the attribute user or user_id.
From the documentation:
Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column) However, your code should never have to deal with the database column name, unless you write custom SQL. You’ll always deal with the field names of your model object.
Not sure but problem causing here in these two line
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
Better to use "related name" attribute to avoid the duplicate error as in database "user" will be added as user_id.
user = models.ForeignKey(User, related_name="id_user") # Change the related field as your convenience
user_id = models.IntegerField(null=True, related_name="user_id")
Check if this resolve your issues