Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Ask Question
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'
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
python manage.py migration
Both worked and also runserver works well too.
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
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.
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.
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.
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
–
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()