Django models migrations: error--trying to add a non-nullable field - django

When I makemigrations to my models, the terminal gives a warning of: "You are trying to add a non-nullable field, etc" and asked for 2 options. I must have made migrations 7 times--should I delete the "0001_initial.py", "0002_auto file" as well as the db.sqlite3? I don't need to keep the database information I inputted since I merely only did tests to see if the models worked---I just want to make sure I don't delete the database itself so I can further test my models to see if they're working. Can someone please verify the specific files I would need to delete so I can make migrations? Your help will be much appreciated!
So far my migrations folders look like this: 001_initial.py, 0002_auto file, 0003_auto file, 0004_auto_file, 0005_auto_file, 0006_auto file, and finally 007_order_buyers file----the last file concerns me--I think it's bc I must have clicked option 2. I just merely want to be able to makemigrations and I am wary of my models not working if I delete important files.
models.py
class User(models.Model):
first_name=models.CharField(max_length=100)
last_name=models.CharField(max_length=100)
email=models.CharField(max_length=100)
password=models.CharField(max_length=100)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
class Order(models.Model):
full_name=models.CharField(max_length=100)
cc_number=models.PositiveIntegerField()
exp_date=models.PositiveIntegerField()
cvc=models.PositiveIntegerField()
buyer=models.ForeignKey(User, related_name="bought_tickets", on_delete=models.PROTECT)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)
class Ticket(models.Model):
venue=models.CharField(max_length=100)
quantity=models.PositiveIntegerField()
price=models.DecimalField(default=25.00, max_digits=5, decimal_places=2, null=True, blank=True)
loop=models.CharField(max_length=100)
purchaser = models.ForeignKey(User, related_name="purchases", on_delete=models.PROTECT)
order=models.ForeignKey(Order, related_name="orders", on_delete=models.PROTECT)
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now=True)

Running makemigrations doesn't do anything to the database, so you can back anything out easily if you haven't run migrate. All that makemigrations does is to create a file. If you don't like it, remove it. When it gives you the error about non nullable field, the options are pretty explicit. Just read them:
You are trying to add a non-nullable field 'foo' to bar without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
If you select (1), the cli will next prompt you to submit a default value. After you do that, it clearly tells you that it has created a file, and tells you the name.
If you select (2), nothing happens. They're leaving it up to you to fix the problem, which you can do in the model by either making the field nullable (add null=True in the field definition) or giving it a default (default=...).
I would suggest taking a look in those files to make sure you understand what they are doing. It's all pretty straightforward. Any of them which have not been run yet can be changed. You can edit them directly, or remove and regenerate them.
To see which ones have been run, use showmigrations.

Related

Getting a "The following content types are stale and need to be deleted" when trying to do a migrate. What does this mean, and how can I solve it?

This is my models.py:
class Notification(models.Model):
user = models.ForeignKey(User)
createdAt = models.DateTimeField(auto_now_add=True, blank=True)
read = models.BooleanField(default=False, blank=True)
class Meta:
abstract = True
class RegularNotification(Notification):
message = models.CharField(max_length=150)
link = models.CharField(max_length=100)
class FNotification(Notification):
# same as Notification
pass
When I do python manage.py makemigrations, this is what it says:
Migrations for 'CApp':
0019_auto_20151202_2228.py:
- Create model RegularNotification
- Create model FNotification
- Remove field user from notification
- Add field f_request to userextended
- Delete model Notification
First, it's weird that it says Remove field user from notification because user is still in my Notiication model (so if anyone can figure out why it says that it say 'removing the field user from notification', that would be great!) but nonetheless, when I move on and try to do python manage.py migrate I get this message:
Applying CMApp.0019_auto_20151202_2228... OK
The following content types are stale and need to be deleted:
CApp | notification
Any objects related to these content types by a foreign key will also
be deleted. Are you sure you want to delete these content types?
If you're unsure, answer 'no'.
Type 'yes' to continue, or 'no' to cancel: no
I typed no. But what exactly does this mean, why am I getting this message and how do I make it so that I don't require this message?
The message you get is triggered when you remove/delete a model and do a migration.
In most cases, you can delete them safely. However, in some cases this might result to data loss. If other models have a foreign key to the removed model, these objects will also be deleted.
Here's the django ticket that requests to make deleting stale content types safer.
EDIT
As #x-yuri pointed, this ticket has been fixed and has been released in Django 1.11.

Slugfield in tango with django

I'm reading this tutorial to lear the basics of django and I'm facing a problem I can't solve.
I'm at this page http://www.tangowithdjango.com/book17/chapters/models_templates.html at the sluglify function approach.
In the tutorial the author says we have to create a new line in our category model for th slugfield. I folow strictly all the steps just as I show here:
from django.db import models
from django.template.defaultfilters import slugify
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
likes = models.IntegerField(default=0)
views = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
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
When I run the "makemgiration" command everything works as expected: I choose the first option and provide ‘’ . BUT when I run "migrate" I get:
django.db.utils.Integrity error: Slug column is not unique
What is going on here? I've repeated several times the migrations and tried other default codes but with the same ending. I can't figure out what im doing wrong. They only thing left is that i'm giving something else instead of ‘’ (Firstly I thoughtthey were '' or ").
Thankyou for your time and help!
Delete db.sqlite3 and re run
python manage.py syncdb
Then perform the migrations
python manage.py makemigrations rango
python manage.py migrate
and re run your population script. This is a downside of Django that whenever you change models.py the db must be recreated.
I am also going through the tutorial and I was having the same issue a couple days ago.
I believe the problem is that you are trying to add a new field (slug) and have it be unique for each of the elements in your table but if I'm not mistaken you already have some data in your table for which that value does not exist and therefore the value that this field would get for those rows is not unique, hence the "django.db.utils.Integrity error: Slug column is not unique".
What I did was simply to delete the data in the table (because it was only a couple of fields, so no big deal) and THEN perform the addition of the field to the model. After doing that, you can put the data back in the table (if you're following the tutorial you should have a script for automated table population so you just run that script and you're golden). Once you have done that, all the rows in the table should have a unique slug field (since it is automatically generated based on the category name) and that solves the problem.
Note that if your table is very large, this may not be a very good solution because of the deletion of data so perhaps there is a better way, like adding that field to the model without it being unique, then running a script that sets the slug field for every row to an unique value and then setting the model's field as unique but I'm not very knowledgeable on SQL and the first solution worked just fine for me so it should work for you as well.
try deleting the sqlite3.db file from the project's directory. i was stuck on a similar problem and that really works..also even if you modify your population script, you have to delete and the recreate the db file to see the changes made....

OneToOne relation with the User model (django.contrib.auth) without cascading delete

I'm a bit confused about how the OneToOneField works when deletion comes into play. The only quasi-authoritative info I can find is from this thread on django-developers:
I don't know if you discovered this yet, but the delete is working in
one direction, but not in the direction you're expecting it to. For
instance, using the models you posted in another message:
class Place(models.Model):
name = models.CharField(max_length = 100)
class Restaurant(models.Model):
place = models.OneToOneField(Place, primary_key=True)
If you
create a Place and a Restaurant that is linked to it, deleting the
Restaurant will not delete the Place (this is the problem you're
reporting here), but deleting the Place will delete the Restaurant.
I have the following model:
class Person(models.Model):
name = models.CharField(max_length=50)
# ... etc ...
user = models.OneToOneField(User, related_name="person", null=True, blank=True)
It's set up this way so I can easily access person from a User instance using user.person.
However, when I try to delete a User record in admin, naturally it's cascading backwards to my Person model, just as the thread discussed, showing something along the lines of:
Are you sure you want to delete the user "JordanReiter2"? All of the following related items will be deleted:
User: JordanReiter
Person: JordanReiter
Submission: Title1
Submission: Title2
Needless to say I do not want to delete the Person record or any of its descendants!
I guess I understand the logic: because there is a value in the OneToOne field in the Person record, deleting the User record would create a bad reference in the user_id column in the database.
Normally, the solution would be to switch where the OneToOne field is located. Of course, that's not realistically possible since the User object is pretty much set by django.contrib.auth.
Is there any way to prevent a deletion cascade while still having a straightforward way to access person from user? Is the only way to do it creating a User model that extends the django.contrib version?
Update
I changed the model names so hopefully now it's a little clearer. Basically, there a thousands of Person records. Not every person has a login, but if they do, they have one and only one login.
Turns out that both ForeignKey and OneToOneField have an attribute on_delete that you can set to models.SET_NULL, like so:
class Person(models.Model):
name = models.CharField(max_length=50)
# ... etc ...
user = models.OneToOneField(User, on_delete=models.SET_NULL, related_name="person", null=True, blank=True)
This results in the behavior I was wanting: the User model is deleted without touching the Person record. I overlooked it because it's not explicitly listed under OneToOneField, it simply says
Additionally, OneToOneField accepts all of the extra arguments accepted by ForeignKey...
Easy to miss.
For this use case you should use a simple ForeignKey. OneToOne means there is one, and can only be one and it can only be associated with this one specific other object. The deletion occurs because it doesn’t make sense to have a null onetoone field, it CAN'T be associated with anything else.

ManyToManyField and South migration

I have user profile model with M2M field
class Account(models.Model):
...
friends = models.ManyToManyField('self', symmetrical=True, blank=True)
...
Now I need to know HOW and WHEN add each other as a FRIEND
And I created a model for that
class Account(models.Model):
...
friends = models.ManyToManyField('self', symmetrical=False, blank=True, through="Relationship")
...
class Relationship(models.Model):
""" Friends """
from_account = models.ForeignKey(Account, related_name="relationship_set_from_account")
to_account = models.ForeignKey(Account, related_name="relationship_set_to_account")
# ... some special fields for friends relationship
class Meta:
db_table = "accounts_account_friends"
unique_together = ('from_account','to_account')
Should I create any migration for this changes or not ?
If you have any suggestions you are feel free write their here.
Thanks
PS: accounts_account table already contain records
First off, I'd avoid using the db_table alias if you can. This makes it harder to understand the table structure, as it is no longer in sync with the models.
Secondly, the South API offers functions like db.rename_table(), which can be used by manually editing the migration file. You can rename the accounts_account_friends table to accounts_relation (as Django would name it by default), and add the additional columns.
This combined gives you the following migration:
def forwards(self, orm):
# the Account.friends field is a many-to-many field which got a through= option now.
# Instead of dropping+creating the table (or aliasing in Django),
# rename it, and add the required columns.
# Rename table
db.delete_unique('accounts_account_friends', ['from_account', 'to_account'])
db.rename_table('accounts_account_friends', 'accounts_relationship')
# Add extra fields
db.add_column('accounts_relationship', 'some_field', ...)
# Restore unique constraint
db.create_unique('accounts_relationship', ['from_account', 'to_account'])
def backwards(self, orm):
# Delete columns
db.delete_column('accounts_relationship', 'some_field')
db.delete_unique('accounts_relationship', ['from_account', 'to_account'])
# Rename table
db.rename_table('accounts_relationship', 'accounts_account_friends')
db.create_unique('accounts_account_friends', ['from_account', 'to_account'])
models = {
# Copy this from the final-migration.py file, see below
}
The unique relation is removed, and recreated so the constraint has the proper name.
The add column statements are easily generated with the following trick:
Add the Relationship model in models.py with foreign key fields only, and no changes to the M2M field yet.
Migrate to it
Add the fields to the Relationship model.
Do a ./manage.py schemamigration app --auto --stdout | tee final-migration.py | grep column
Revert the first migration.
Then you have everything you need to construct the migration file.
The way you've got it coded there, you're manually defining a model which does the same job as the m2m join table that Django will have automatically created for you. The thing is, the automatically created table will be called accounts_relationship_friend.
So, what you're doing there will create a model that tries to duplicate what the ORM has done under the surface, but it's pointing at the wrong table.
If you don't need an explicit join model, I would leave remove it from your codebase and not create a migration to add it, and instead use the M2M to find relationships between friends. (I'm not thinking about this too deeply, but it should work).
If, however, you want to do something special with the Relationship model you have (eg store attributes about the type of relationship, etc), I would declare the Relationship model to be the through model you use in your Friend.friends m2m definition. See the docs here.

Creating Custom User Backends in Django

I have a Shops model and would like each shop to be able to login to my application. Following as best I can the guide at http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/ and various other googlings, I've got part of the way there, but I've run into a problem. When I try to login as a shop, I get the following error:
OperationalError at /login/
(1054, "Unknown column 'shops.user_ptr_id' in 'field list'")
Shops model:
class Shops(User):
shop_id = models.AutoField(primary_key=True)
shop_code = models.CharField(unique=True, max_length=5)
shop_type_fk = models.ForeignKey(ShopTypes,
null=True,
db_column='shop_type_id',
blank=True)
address_fk = models.ForeignKey(Addresses, db_column='address_id')
phone_number = models.CharField(max_length=30)
#email = models.EmailField(max_length=255, blank=True)
description = models.TextField(blank=True)
does_gift_aid = models.NullBooleanField(null=True, blank=True)
objects = UserManager()
class Meta:
db_table = u'shops'
I've sync'd the database, so surely it should have made the column user_ptr_id. Does anyone know where I'm going wrong?
"I've sync'd the database, so surely it should have made the column user_ptr_id."
What makes you think that? Especially in light of this clear statement in the docs for syncdb:
Syncdb will not alter existing tables
syncdb will only create tables for
models which have not yet been
installed. It will never issue ALTER
TABLE statements to match changes made
to a model class after installation.
Changes to model classes and database
schemas often involve some form of
ambiguity and, in those cases, Django
would have to guess at the correct
changes to make. There is a risk that
critical data would be lost in the
process.
If you have made changes to a model
and wish to alter the database tables
to match, use the sql command to
display the new SQL structure and
compare that to your existing table
schema to work out the changes.
It does sound like you had an existing shops table before changing it to inherit from User (as Daniel notes), and syncdb does not update the schema for existing tables.
You need to drop the table and then run syncdb, if possible. Otherwise you need to go into your database and add the user_ptr_id field manually, if you know how to do that. The definition should look something like this:
"user_ptr_id" integer NOT NULL UNIQUE REFERENCES "auth_user" ("id")