I am following a tutorial as I am fairly new to Django, and I am trying to add a comments system to my blog. However, whenever I try and use it I get an error message saying the following:no such column: blog_comment.body. I am not sure what is going on, as in my model I have body = models.TextField(), and I am just generally very confused.
This is because you have not run migrations in order to apply the body column to the database.
Just run ./manage.py makemigrations and ./manage.py migrate
Django will ask you to enter a default value since you have declared the body field as not nullable.
If you don't want to enter a default value, write it like this:
body = models.TextField(blank=True, null=True)
and then run the same commads.
Related
I had a field in my model with
book_classes = (("","Select Form"),("1",'F1'),("2",'F2'),("3",'F3'),("4",'F4'),("All Forms","All Forms"))
b_classes = models.CharField('Form',max_length=9,choices=book_classes,default="n/a")
And then changed it to
b_class =models.ForeignKey(ClassBooks,on_delete=models.CASCADE)
Where
class ClassBooks(models.Model):
name = models.CharField(max_length=10)
I'm now stuck because when I try to migrate I get an error.
Invalid input syntax for type bigint:"All Forms"
Makemigrations and migrate worked well in development. When I pushed to digital ocean, the migrate returned the error stated.
What do I need to do, please?
See Foreign Key field. By default a FK field is going to use the Primary Key of the referenced table(model), in this case the id field of ClassBooks. The id field is an integer so you get the error when trying to use a string field. To make this work, from the documentation link :
ForeignKey.to_field
The field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have unique=True.
Which in your case becomes:
b_class =models.ForeignKey(ClassBooks,to_field='name',on_delete=models.CASCADE)
This assumes that the name field has a Unique constraint on it.
Though I am not sure how "", "1", "2" ... map to ClassBooks.name.
If you dont want to lose db.sqlite3 try to delete migrations first
Step 1: Delete the db.sqlite3 file.
Step 2 : $ python manage.py migrate
Step 3 : $ python manage.py makemigrations
Step 4: Create the super user using $ python manage.py createsuperuser
new db.sqlite3 will generates automatically
In my Django app, I want to insert a record with a composite primary key. Apparently this should be possible by making use of "unique_together". I'm quite sure this code was working in the past, but for some reason it does not seem to be working now. This code used to run on a Linux VM, and now I'm hosting it in Google App Engine. However I don't see how this can be the cause for this error.
class TermsAndConditionsDocument(models.Model):
organization = models.ForeignKey(Organization, on_delete=models.CASCADE, verbose_name=_("Organization"))
language = models.CharField(_('Language'),choices=LANGUAGE_CHOICES, max_length=5, help_text=_("The language of the content."))
content = models.TextField()
class Meta:
unique_together = ('organization', 'language')
The error:
IntegrityError at /transactions/settings/terms_and_conditions
null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, nl-BE, <p>B</p>, 10).
According to what I've read, using "unique_together" should cause Django to not need or include an ID as primary key. I checked the database, and the ID field DOES exist. I do not understand where the database constraint and the ID field are still coming from?
Apparently, as pointed out in the comments, a primary key "id" field is always added, even if you don't need it. It's supposed to get out of your way, so you don't even notice its existence. In my case, it required me to give it a value when I created a new record, which is not how things are supposed to work.
A while back I migrated this database from one Postgres database to another Postgres database. I used an SQL dump and load method for this. Some sequences seem to have been lost during that migration.
Because there are no sequences, some fields now lacked autoincrement capabilities, explaining the IntegrityError on insertion.
In order to fix this, I did the following:
1) Export the current data:
manage.py dumpdata > data.json
2) Drop your database and create a new empty one.
3) Run database migrations:
manage.py migrate
4) Load the data again, excluding some default data already recreated by Django.
manage.py loaddata --exclude auth.permission --exclude contenttypes data.json
This procedure seems to have recreated the sequences while also keeping the data.
The unique_together only creates a DB constraint (https://docs.djangoproject.com/en/2.2/ref/models/options/#unique-together).
You could create a custom primary key with the option primary_key https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.Field.primary_key but you could only do that for one field.
But I suggest to just keep the auto increment id field, this works better with Django.
For the error are you saving a model? or doing a raw import?
Django 2.0
I've created a model in Blog app,
class Category(models.Model):
field1 = models....
field2 = models....
field3 = models....
and after some time I want to add a new field in that model.
class Category(models.Model):
field1 = models....
cover_pic = .models....
field2 = models....
field3 = models....
I followed this answer. But it gives me the following error.
django.db.utils.OperationalError: (1054, "Unknown column 'blog_category.cover_pic' in 'field list'")
That answer is from 2014 and for an old Django version.
The workflow for adding new fields is simple:
Write code for the field in your model.
Run command manage.py makemigrations.
Run command manage.py migrate.
This is all in the documentation.
Since, you already followed that answer and have run the manage.py --fake command, you have messed up your db state a little bit.
To recover, do this:
Go to your "blog" app's "migration" folder.
Look at the names of the migration files. They should look like 0001_category_field1.py, 0002_category_cover_pic.py.
The faked migration will be the one with name something like 0002_category_cover_pic.py. Note its number, like 0002.
Now you'll have to move back to the previously applied migration. So, if the faked migration number is 0002, the previously applied migration will be 0001.
Now run this command - manage.py migrate --fake myapp 0001. Note the number of the migration file. You'll have to fake another migration back to the previously applied migration file.
Now run command - manage.py migrate myapp.
This should fix your problem.
If you're problem is not solved yet and you don't have important data in your database, I would suggest start your database from fresh. Delete all your database tables, then delete all the migration files inside your app_name/migration folders. Now run the two commands and start developing.
python manage.py makemigrations
python manage.py migrate
Now you will have a fresh database and you are good to go. From next time try to follow the way mentioned in the above comment.
If you are adding a new field in the Django model and after deploying to any environment , you are getting error while accessing the field.
Error:
"1054, Unknown column"
Although i also was not able to figure out how to resolve it but i came up with a work around.
I created a column manually in the DB .
I added the same field in the model.
Again tried to access the field and it worked like a charm.
I hope it helps your case.
I have a model that have a URLField field and I need to make a migration that turns this field into a foreign key, where the string is a unique field of the other object, and, if the object does not exist create it.
for example, turn this:
class Event_UserVisit(Event_Base):
dest_url = models.URLField(max_length=1000)
into this:
class Event_UserVisit(Event_Base):
dest_url = models.ForeignKey(Page)
I've never done a manual migration like this and didn't find any tutorial or instructions to do something like this.
obviously doing a naive migration return errors like this:
django.db.utils.ProgrammingError: column "source_url_id" cannot be cast automatically to type integer
what's the best approach to do it?
note: I need to do this on a production db with lots of data, so I can't have long down time and can't lose any data.
thanks! :)
I don't think you can do this at the ORM level in one go (unless someone corrects me) You would need create a new FK maybe dest_url2 run migrations, then write a script to migrate the data. Next,delete dest_url again run migrations. Then rename dest_url2 to dest_url Django will detect the name change here.
However, I don't understand why you are linking an FK ID on page to a field called dest_url. A PK in Page should not be a 1000 max URL! It has no order and would make indexing hard and slow down your app. It would make more sense do have...
class Event_UserVisit(Event_Base):
page = models.ForeignKey(Page, related_name='eventvisits')
The I assume Page looks something like this...
class Page(models.Model):
dest_url = models.URLField(max_length=1000)
I am doing a migration that adds a referral code to my custom user model. The field I've added looks like this:
refer_code = models.CharField(max_length=10, default=UUID_10)
In my datamigration I've added the following:
for u in orm['app.User'].objects.all():
u.refer_code = UUID_10()
print u.name + ': ' + u.refer_code
u.save()
However, when I perform the migrations, all of my users have the same code. Different codes for each user are spat out from the print command, so it's not a problem with my function.
Weirdly, if I roll the datamigration back (it has no backwards method) as well as the previous migration that added the field, and re-apply them, not only does every model have the same data in, it exactly has the same data in as before.
There are other parts of the datamigration (adding objects to the database with get_or_create) that are working fine.
What on earth is going on?
I think your function was called rather than new field was created. So try to do two migrations. First add new field with default value. And second fill that field.