django.db.utils.IntegrityError: NOT NULL constraint failed: products_product.image ERROR WITH IMAGE FIELD
Asked Answered
S

15

30

I wanna add ImageField to my Product model and upload it to my media_cdn directory but when I migrate my base to my model.py it returns the below error:

django.db.utils.IntegrityError: NOT NULL constraint failed: products_product.image ERROR WITH IMAGE FIELD

The exact output from cmd is:

    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards
    field,
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\sqlite3\schema.py", line 231, in add_field
    self._remake_table(model, create_fields=[field])
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\sqlite3\schema.py", line 199, in _remake_table
    self.quote_name(model._meta.db_table),
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\base\schema.py", line 112, in execute
    cursor.execute(sql, params)
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\utils\six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "C:\Users\PANDEMIC\Desktop\td10\lib\site-packages\django\db\backends\sqlite3\base.py", line 337, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: products_product.image

Here is my models.py module:

from django.db import models

# Create your models here.

class Product(models.Model):
    name = models.CharField(max_length=40)
    description = models.TextField(max_length=220, blank=True, default=None)
    image = models.ImageField(upload_to="/products_images/", null=True, blank=True, width_field="width_field", height_field="height_field")
    width_field = models.IntegerField(default=0)
    height_field = models.IntegerField(default=0)
    is_active = models.BooleanField(default=True)
    publish = models.DateField(auto_now=False, auto_now_add=True)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
    
    def __str__(self):
        return "%s" % self.id

    class Meta:
        ordering = ["-timestamp"]
        verbose_name = 'Product'
        verbose_name_plural = 'Products'
Shapeless answered 11/3, 2017 at 8:48 Comment(0)
S
17

need just delete your base and make migrations your app

Shapeless answered 11/3, 2017 at 10:31 Comment(0)
G
41

Go to the migrations folder and delete manually files that have 000*_lastAction_blah-blah type of name, you can delete, probably all, but 0001_initial.py file. After that run ./manage.py make migrations app_you_are_updateing, it should update your database.

Germen answered 10/1, 2019 at 19:21 Comment(0)
S
17

need just delete your base and make migrations your app

Shapeless answered 11/3, 2017 at 10:31 Comment(0)
T
10

Have you run makemigrations [appname] yet?

NOT NULL constraint failed

This error usually means that a field that is required was not provided, but I can see that you have set the blank=True and null=True attributes in your image field.

Thorin answered 11/3, 2017 at 8:55 Comment(0)
D
8

Similar issues we face too, I locally checked with removing blank=true,null=true works, but in production server it did not works well.

Than files inside app where issue raise, their a migration folder, I had removed all files and then

python manage.py makemigrations

and

python manage.py migration

Both worked and also runserver works well too.

Donnetta answered 29/9, 2017 at 21:19 Comment(0)
B
7

Go to migrations folder of your project and delete the migration file created because of the command: python manage.py makemigrations and re run the same command and then run:

python manage.py migrate
Blunk answered 8/3, 2019 at 9:2 Comment(0)
D
6

If you have added a field to a model (or have modified a field), when you migrate, Django will look up the previous records and check whether they meet the constraints given for the field.

In your case, even if you have allowed null = True for the ImageField, when Django tries to add that column to the database, it finds that value for that field has 'not been defined' for previous records.

Solution: you have to add default = None in the ImageField, which will make the values for previous records NULL.

Moreover, when Django runs migrations, even if you specify the migration number (for instance, python manage.py migrate your_app_name 00xx), it checks for dependencies in previous migrations. Now, as the migration you have made here has caused an error, even if you correct it (as given) and try to migrate, it will still cause the same error.

Therefore, you need to remove all previous migrations up to the one which caused the error first, and run makemigrations again. Then you can run migrate without a problem.

Dikdik answered 31/3, 2020 at 9:53 Comment(0)
D
0

Basically if you have made changes in your model class , you need to delete all the objects created before , since they have old attributes.

Dismiss answered 15/8, 2018 at 11:10 Comment(1)
Nop, thanksfully thereis the makemigrations commande to update the object :)Pitanga
S
0

Simply go to the migrations folder, delete all the .py files, and then run the command python manage.py makemigrations and python manage.py migrate again.

Sanguinolent answered 12/7, 2020 at 9:37 Comment(2)
Nuking all migrations isn't a very good solution, is it?Passus
Apparently, it is the only solution to solve this type of error. And, it is not bad at all because, as would already know, migrations are created automatically every time we make changes to database. So, it would not cause any difference.Sanguinolent
B
0

If you have previously created a form in Django, you can check the fields associated with the form (fields = ['title', 'content', 'author'] etc.), maybe you have not added a field with a not null constraint in your model.

models.py

class Task(models.Model):
    author = models.ForeignKey("auth.User", on_delete=models.CASCADE, verbose_name='Taskı Oluşturan')  # user
    title = models.CharField(max_length=150, verbose_name='Task Başlık')
    content = models.TextField(verbose_name='Task İçeriği')
    created_date = models.DateTimeField(auto_now_add=True, verbose_name='Task Oluşturulma Tarihi')  # o anki tarihi atar
    slug = models.SlugField(editable=False)
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="task")
    tag = models.ManyToManyField(Tag, related_name="task", blank=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(Task, self).save(*args, **kwargs)

views.py 

@method_decorator(login_required(login_url='/user/login'), name="dispatch")
class CreateTaskView(CreateView):
    template_name = 'task/create_task.html'
    form_class = TaskCreationForm
    model = Task


    def get_success_url(self):
        return reverse('detail',kwargs={"pk":self.object.pk, "slug":self.object.slug})

  
    def form_valid(self, form):
        form.instance.user = self.request.user
        form.save()
    
        tags = self.request.POST.get("tag").split(",") 

        for tag in tags:
            current_tag = Tag.objects.filter(slug=slugify(tag))

            if current_tag.count() < 1:
                create_tag = Tag.objects.create(title=tag)
                form.instance.tag.add(create_tag)

            else:
                exist_tag = Tag.objects.get(slug=slugify(tag))
                form.instance.tag.add(exist_tag)

        return super(CreateTaskView, self).form_valid(form)

forms.py

class TaskCreationForm(forms.ModelForm):

    class Meta:
        model = Task

        widgets = {
            'title':forms.TextInput(attrs={'class':'form-control', 'placeholder':'Title'}),
            'content':forms.Textarea(attrs={'class':'form-control', 'placeholder':'Content Here'})

        }

        fields = ['author','title','category','content']

I got the same error when I didn't add the 'author' field.

Bismuthinite answered 15/10, 2020 at 8:15 Comment(0)
W
0

I know that it has been a long time since you published this and maybe you have more experiences, but your problem would be solved quickly, if only you were to do a ./manage.py makemigrations, and after that I would have to leave something like this:

You are trying to add a non-nullable field 'user' to tweet 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:

Where you were put 1, after you got this other:

Please enter the default value now, as valid Python
The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now
Type 'exit' to exit this prompt

Where it was also put 1, and with all that ready you will only be made a ./manage.py migrate, and with that your problem would be solved without anything else to say I slowly withdraw.

oh and if you did all that and you had no result, it's because you have to create a superuser and if you don't know, you just go to the terminal and put ./manage.py createsuperuser, you create the user and after that you go and repeat what already said and I think that with that I would be super relaxed.

Withal answered 17/12, 2020 at 16:27 Comment(0)
F
0

I had the same error message: "django.db.utils.IntegrityError: NOT NULL constraint failed: appName_modelName.model_field_id" I deleted migration files and DB but with no success. It turned out that I forgot to add one filled to the form class in forms.py

Fibroid answered 14/4, 2021 at 17:20 Comment(0)
E
0

I Had the same problem. I deleted all migrations except __init__.py, then I deleted the database and after that just make migrations and migrate and then all things went fine.

Economical answered 24/8, 2021 at 17:47 Comment(0)
S
0

It might also be the result of saving an instance of a model without specifying the values for required fields, for example:

class TestModel(models.Model):
    test1 = models.CharField(max_length=4)
    test2 = models.CharField(max_length=4)

and somewhere (probably in your views.py) the model is saved without specifying certain values:

model = TestModel()
model.test1 = 'beer'
model.save()
Sexpot answered 3/2, 2023 at 20:16 Comment(0)
E
0

It happens when you newly create or add a field to your model class and do migrtations but the problem occurs when migrate it, since your earlier instances have not included those fields that you newly added it. just do run these commands below, and let me know please if you get any problem after doing this.python3 manage.py migrate --fake then, now migrate it with the usual migrate command as follows before;

python3 manage.py migrate
Evangelista answered 26/4, 2023 at 3:41 Comment(0)
H
0

I got the same errors below, when I tested with pytest-django and pytest-factoryboy in Django:

django.db.utils.IntegrityError: NOT NULL constraint failed: my_app3_product.category_id

django.db.utils.IntegrityError: NOT NULL constraint failed: my_app3_product.price

Because even though I set category and price fields which have NOT NULL constraint to Product class as shown below:

# "my_app1/models.py"

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=255)

class Product(models.Model):
    name = models.CharField(max_length=255)
    category = models.ForeignKey(Category, on_delete=models.RESTRICT) # Here
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=5, decimal_places=2) # Here

Then, I did not set category and price fields to ProductFactory class in factories.py as shown below:

# "factories.py"

import factory
from my_app1.models import Category, Product

class CategoryFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Category

    name = "django"

class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Product

    name = "product_name"
    # category = factory.SubFactory(CategoryFactory) # Here
    # price = '4.99' # Here

So, I set category and price fields to ProductFactory class in factories.py as shown below, then the error was solved:

# "factories.py"

import factory
from my_app1.models import Category, Product

class CategoryFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Category

    name = "django"

class ProductFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Product

    name = "product_name"
    category = factory.SubFactory(CategoryFactory) # Here
    price = '4.99' # Here
Hagerman answered 13/8, 2023 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.