Why am I getting IntegrityError: NOT NULL constraint failed - python

IntegrityError: NOT NULL constraint failed: app_userprofile.email
The field looks like this:
email = models.CharField(max_length=100, blank=True, default=None)
I do not understand. Error happens when creating instance of the model and not setting the email field. But it's blank and it's charfield, and None if not overwritten, why is it happening?

There are two option:
set null = True which is used if you want to save null value in Database.
set blank = True which is used for form validation. You can call save form without value in that field.
In your current issue you just have to add null = True.
email = models.CharField(max_length=100, blank=True, null=True, default=None)

As noted here, using null=True in charField and TextField should be avoided. Because then your field has two options for no data. one is None another is blank string.
By the way null is by default set to False in django fields and you should set it to True in your case.

Related

Django is putting empty string by default while expecting it to be null in DB column

I am using postgresql version 10.6 with my Django 2.1 application. The problem is that when I am using null=True in my model field it is translating to empty string ('') in database column as default where I am trying default it as null.
In my following code sample image column should be null:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(upload_to='profile_pics', null=True, blank=True)
And I am calling this class from a signal like this:
#receiver(post_save, sender=User)
def create_profile(sender, **kwargs):
if kwargs.get('created') is True:
Profile.objects.create(user=kwargs.get('instance'))
In this snapshot you can see that image column is inserting as empty string instead of null
I have also tried to use default value for my model field as:
image = models.ImageField(default=None, upload_to='profile_pics', null=True, blank=True)
but it doesn't work either.
image = models.ImageField(upload_to='profile_pics', null=True)
remove the blank=True
Null: It is database-related. Defines if a given database column will accept null values or not.
Blank: It is validation-related. It will be used during forms validation when calling form.is_valid().
The default values of null and blank are False.
You should remove blank=True

NOT NULL constraint failed error in django despite having null set to true and blank set to true

Here's the code:
class community(models.Model):
communityName = models.CharField(max_length=280)
communityID = models.BigIntegerField(null=True,blank=True)
icon = models.CharField(max_length=400)
def __str__(self):
return self.communityName
class team(models.Model):
date = models.DateField()
startTime = models.TimeField()
teamName = models.CharField(max_length=280)
community = models.ForeignKey(community, on_delete=models.CASCADE, default=None)
I've done a lot of reading on this and it makes sense that I'm supposed to set null and blank to true to prevent this error however when I attempt to migrate the models I still get the following error thrown:
django.db.utils.IntegrityError: NOT NULL constraint failed: scheduler_team.community_id
I don't know anything about database management and this is the first project I've attempted to do that has a database involved so an ELI5 would be very much appreciated thank you!
Make it like this in your team model:
community = models.ForeignKey(community, on_delete=models.CASCADE, blank=True, null=True)
This is the proper way to make it nullable.
When you specify default=None, Django ORM does not know if this field is nullable or not.
community_id is the field in team model and it is (though syntactically implicit) used to refer community model by the foreign key in team model, and that field was set as not nullable, so that generates IntegrityError, if not set.

Django IntegrityError while updating a record

I have a model with double columns as primary key. I do a filter on it and get the records I want, change a field and save it. As I know save will update the record and does not create a new instance of the model in db. so It should be all okay but I'm stuck with an integrityError Duplicate entry '10-2' for key 'PRIMARY' when I try to save the record
Here is the code snippet:
analysis = AnalysisResult.objects.filter(request=req.request_id)
for anal in analysis:
anal.analysisresult_path = some_string
anal.save() #this line is where the error occurs
And here is my model:
class AnalysisResult(models.Model):
analysisresult_path = models.CharField(db_column='analysisResult_path', max_length=255, blank=True,
null=True) # Field name made lowercase.
detectionresult_path = models.CharField(db_column='detectionResult_path', max_length=255, blank=True,
null=True) # Field name made lowercase.
targetcode = models.ForeignKey('TagetCode', models.DO_NOTHING,
db_column='targetCode_id') # Field name made lowercase.
request = models.ForeignKey('Request', models.DO_NOTHING, primary_key=True)
class Meta:
managed = False
db_table = 'analysis_result'
unique_together = (('request', 'targetcode'),)
Ah, yes, welcome to one of django's strongest opinions: all tables/models should have a single primary key field that can be used for updates. If you don't have this, you must write raw SQL for the update since save will assume that there is an implicit primary key field called id to use in the where clause.

django boolean default not respected when not specifically excluded in form

I'm using django 1.5.
In my model definition, I have a boolean field with default=True defined. However, when a record is saved using my modelForm, the value is not saved as True with the record; it is saved as False.
forms.py
class ExampleForm(forms.ModelForm):
hours = forms.DecimalField(required=False,
max_digits=5,
decimal_places=2,
widget=forms.TextInput(attrs={'placeholder':'3.5'}))
class Meta:
model = Example
exclude = ('fk')
models.py
class Example(models.Model):
id = models.AutoField(primary_key=True)
fk = models.ForeignKey(FK)
hours = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
active = models.BooleanField(default=True)
They way this is set up to me it would seem that since active is not provided by the form that there is no value supplied when validating the record, therefore it should default to the default value set in the model. That is NOT the case. It defaults to False. However, I notice that if I explicitly add it to excluded fields, then the default does stay at True. I.e. if I change this line exclude = ('fk') to exclude = ('fk','active') and change nothing else, the validation works as I would expect.
Is this the correct behavior? My assumption that if a model field is not specified in the form it will use the default value defined in the model is wrong? This seems counterintuitive to me... just want to make sure I'm not missing anything.

Django EmailField accepts any value (including blank)

Having this Django model:
class Subscriber(models.Model):
email = models.EmailField(unique=True, blank=False)
I do not face any exceptions when creating a Subscriber with empty email:
>>> Subscriber.objects.create(email='')
<Subscriber: Subscriber object>
Interesting is that for the second time it will raise the IntegrityError:
>>> Subscriber.objects.create(email='')
...
IntegrityError: column email is not unique
So it seems to validate for integrity, but neither for email format nor for blank entries. How do I have the email validated?
The parameter blank is used from the form, it's not enforced at database level
From the documentation
Field.blank If True, the field is allowed to be blank. Default is
False.
Note that this is different than null. null is purely
database-related, whereas blank is validation-related. If a field has
blank=True, form validation will allow entry of an empty value. If a
field has blank=False, the field will be required.
Indeed the validator documentation says that
Note that validators will not be run automatically when you save a model
to enforce that you have to use the full_clean() method.
The error is thrown because you are trying to insert two times the empty string and you have
the unique constraint on the field.
you got to validate your e-mail field with a built in email-validator like this
from django.core.validators import validate_email
and declare your e-mail field in this way
email = models.EmailField(unique=True, validators=[validate_email,])
this way it will validate your e-mail field with a built in regular expression

Categories