django not nullable error on model field containing null-True - django

So i have a user that can post comments on effects, im linking up my models and i keep getting the non-nullable error no matter what ive tried. Everyone says it needs to have null=True. It isn't working lol. What am I not seeing here?
This is the official error:
django.db.utils.IntegrityError: NOT NULL constraint failed: effect_modules_comment__new.author_id
And my models:
class Effect_module(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=255)
description = models.TextField()
html = models.TextField(default='')
css = models.TextField(default='')
js = models.TextField(default='')
up_votes = models.IntegerField()
down_votes = models.IntegerField()
effect_author = models.ManyToManyField('UserProfile')
class UserProfile(models.Model):
user = models.OneToOneField(User)
effects = models.ManyToManyField(Effect_module)
class Comment(models.Model):
comment_author = models.ForeignKey(User, null=True)
comment = models.TextField(default='No Comment Here')
effect_object = models.ForeignKey(Effect_module)

Delete all migration scripts. Add null=True means it can be NULL in the database, blank=True means that it can be left blank in forms.
Then
python manage.py makemigrations
python manage.py migrate

Related

Author page in django migrations and questions

I want to make a website for eBooks with a page that has all the books published by one of the authors. The problem is that I have no idea how to do that. I will mention that I am a beginner.
I tried this int the model file
class Author(models.Model):
author = models.TextField()
class Product(models.Model):
…
author=models.ForeignKey(Author,on_delete=models.CASCADE)
The result in the terminal was:
File "/home/user/petnet/petnet-env/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 264, in check_constraints
raise IntegrityError(
django.db.utils.IntegrityError: The row in table 'store_product' with primary key '2' has an invalid foreign key: store_product.author_id contains a value 'anonim' that does not have a corresponding value in store_author.id.
I think this is caused by the act that I made the author field later and there were already authors fields from before, but then, when I tried to revert back to what I had before doing this, I got some errors regarding migrations.
Also the views were:
def author_detail(request, slug):
author = get_object_or_404(Author, slug=slug)
products = author.products.filter(status=Product.ACTIVE)
return render(request, 'store/author_detail.html', {
'author':author,
'products':products
})
But I am also curious if there is a chance I could use only this for models so I could use the form for adding a product in a much easier way.
class Product(models.Model):
DRAFT = 'draft'
WAITING_APPROVAL = 'waitingapproval'
ACTIVE = 'active'
DELETED = 'deleted'
STATUS_CHOICES = (
(DRAFT, 'Ciorna'),
(WAITING_APPROVAL, 'Asteapta aprobare'),
(ACTIVE, 'Activ'),
(DELETED, 'Sters')
)
user = models.ForeignKey(User, related_name='products',on_delete=models.CASCADE)
category=models.ForeignKey(Category, related_name='products',on_delete=models.CASCADE)
title = models.CharField(max_length=50)
image = models.ImageField(upload_to='uploads/product_images/', blank=True, null=True)
editie = models.IntegerField()
editura = models.CharField(max_length=50)
description = models.TextField(blank=True)
author = models.TextField(max_length=50)
created_at = models.DateTimeField(auto_now_add=True)
slug = models.SlugField(max_length=50)
status = models.CharField(max_length=50, choices=STATUS_CHOICES, default=ACTIVE)

assert not cls._meta.auto_field, ( AssertionError: Model shop.Product can't have more than one auto-generated field

I got following error:
assert not cls._meta.auto_field, ( AssertionError: Model shop.Product can't have more than one auto-generated field )
Here is my Product class code:
class Product(models.Model):
product_id = models.AutoField(primary_key=True)
product_name = models.CharField(max_length=50)
category = models.CharField(max_length=50, default="")
subcategory = models.CharField(max_length=50, default="")
price = models.IntegerField(default=0)
desc = models.CharField(max_length=300)
pub_date = models.DateField()
image = models.ImageField(upload_to="shop/images", default="")
def __str__(self):
return self.product_name
What Am I doing wrong?
I have the same error, and i resolve doing that:
1 - Move to trash old migrate
2 - run python manage.py makemigrations
3 - run python manage.py migrate
if your problem persist, try to delete table into a data base ( if you do that, you lost your admin user, you can create another with python manage.py createsuperuser

Strange behavior with a foreign key relationship and custom user model

I am working on a django (1.8.6) site that involved two applications now. One is a custom user model with basic registration / login / logout functionality, the second is a feedback application. I want to have a foreign key relationship from a feedback to the user that submitted it.
When I try to run ./manage.py migrate I get the following error.
django.db.utils.ProgrammingError: relation "customauth_user" does not exist
This is of course since the database table does not YET exist. If I remove the related field, everything works fine. Here is my code.
My user model:
class User(AbstractBaseUser):
username = models.CharField(_('username'), max_length=100, unique=True)
email = models.EmailField(('email address'), max_length=254)
first_name = models.CharField(_('first name'), max_length=50)
last_name = models.CharField(_('lat_name'), max_length=50)
receive_newsletter = models.BooleanField(_('receive_newsletter'), default=False)
referral_id = models.CharField(_('referral id'), max_length=40)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email', 'first_name', 'last_name']
And the model from my feedback form:
class Feedback(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
submitted_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='feedback')
title = models.CharField(max_length=100)
message = models.CharField('Users message', max_length=1024)
reviewed = models.BooleanField('Reviewed by staff', default='NEW', choices=FEEDBACK_STATUS_CHOICES, max_length=10)
jira_ticket_created = models.BooleanField('Created a Jira ticket to track this feedback.',
default=False)
jira_ticket_number = models.CharField(max_length=10, blank=True, null=True)
class Meta:
db_table = 'feedback'
def __str__(self):
return str(self.timestamp) + ' ' + self.title
I have configured my user model in settings, added both applications, and in my installed applications my applcaition with my custom user model is first.
Any thoughts?
Thanks
Craig
You need to add a dependency in your feedback migration to the customauth app. See the migrations docs.
You should use python manage.py makemigrations
and then python manage.py migrate

How to migrate data from a field to another in a table using south

Im working on a Django project using south for schema migrations.
I have the following scenario:
schema
class Book(model.Models):
name = models.CharField(max_length=255, blank=True)
bid = models.IntegerField(blank=True, null=True)
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book_id = models.ForeignKey(Book, null=True, to_field="bid", db_column="bookID")
I wanna change Author model to the following:
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book = models.ForeignKey(Book, null=True, db_column="book_id")
but without loose data. I want to search each book by its bid and assign the one found to the new field in Author model.
Thanks
You'll have to do a 3 migrations. A schemamgiration that adds the new book FK, then a data migration and then a schemamigration to delete and rename the fields.
So you'll want to change your models.py file to this:
class Book(model.Models):
name = models.CharField(max_length=255, blank=True)
bid = models.IntegerField(blank=True, null=True)
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
book_id = models.ForeignKey(Book, null=True, to_field="bid", db_column="bookID")
# You don't need the db_column="book_id" since that's what it does at the DB level by default.
# I'm not sure if things will break if you name it book with another field as book_id.
book_new = models.ForeignKey(Book, null=True)
Then run python manage.py schemamigration APP_NAME auto
Then run ```python manage.py datamigration APP_NAME populate_book_id
Then edit the newly created data migration and loop through the Author instances setting the new book field with the book_id field. Don't forget to remove the book field values in the backwards method.
Then change your models.py file to the following:
class Book(model.Models):
name = models.CharField(max_length=255, blank=True)
bid = models.IntegerField(blank=True, null=True)
class Author(model.Models):
name = models.CharField(max_length=255, blank=True)
# You don't need the db_column="book_id" since that's what it does at the DB level by default.
book = models.ForeignKey(Book, null=True)
Then run python manage.py schemamigration APP_NAME auto
You'll want to check this last schemamigration to make sure it's renaming book_new to book and not dropping and creating columns. Here's an answer that explains how to change it.

Database is not changing after a migration

So using south, I wanted to add a new field is_private to one of my models.
Following the tutorial, after changing the models.py file, I should do this:
./manage.py schemamigration reconstructions --auto
which returns:
Added field is_private on reconstructions.Reconstruction
Created 0005_auto__add_field_reconstruction_is_private.py. You can now apply this migration with: ./manage.py migrate reconstructions
Which is great. Now next step is,
python manage.py migrate reconstructions
And that prints:
- Migrating forwards to 0005_auto__add_field_reconstruction_is_private.
> reconstructions:0005_auto__add_field_reconstruction_is_private
- Loading initial data for reconstructions.
No fixtures found.
it seems to be doing it's job. But when I afterwards check the field is_private, Django throws me an error:
Cannot resolve keyword 'is_private' into field.
Which tells me south did not changed the database at all. Why is so?
Extra information:
The model class:
class Reconstruction(models.Model):
id = models.CharField(max_length=36, primary_key=True,
editable=False)
uploader = models.ForeignKey(User, blank=True, null=True)
status = models.TextField(blank=True)
viewcount = models.IntegerField(default=0)
error_flag = models.IntegerField(default=0)
is_done = models.BooleanField(default=False)
create_date = models.DateTimeField(auto_now=True)
last_modified_date = models.DateTimeField(auto_now=True)
is_private = models.BooleanField(default=True)
The code causing the crash:
recordings = Recording.objects.filter(is_done=True).filter(is_private=False).order_by('-create_date')
Observation: you added is_private to Reconstruction, but you're trying to filter Recording objects based on that property. Perhaps this is the issue?