I am creating a telegram bot which is a database. If ‘@usename == None’ it returns django.db.utils.IntegrityError: NOT NULL constraint failed: main_profile.name What should I do ?
Models.py
from django.db import models
class Profile(models.Model):
external_id = models.PositiveIntegerField(
verbose_name='User ID',
unique=True,
)
name = models.TextField(
verbose_name='User name',
default='None'
)
def __str__(self):
return f' ID: {self.external_id} | Username: {self.name}'
class Meta:
verbose_name = 'Profile'
class Message(models.Model):
profile = models.ForeignKey(
to='main.Profile',
verbose_name='Profile',
on_delete=models.PROTECT,
null=True,
)
text = models.TextField(
verbose_name='Text',
)
Forms.py
from django import forms
from .models import Profile
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = (
'external_id',
'name',
)
widgets = {
'name': forms.TextInput
}
2
Answers
You need to delete the last few migrations, you can do all except the
0001_initial.py
. Then just go and dopython manage.py makemigrations your_app_name
and thenpython manage.py migrate
and it should be solvedYou should take a look at the answer above, this problem is almost always related to migration stuff, but in case it don’t, I guess that in the
name
field of yourProfile
model, if you don’t specify the constraintnull=True
, by default it would beFalse
so it is saying that you are obliged to give a value (!= to an empty string), so:if you are doing something like this:
When the the form class receives the
request
if thename
input has no data in it, it would look like{"name" : ""}
, and becouse the request object have the name key first it not going to use thedefault='None'
and then is going to pass it to thecreate
method in the form, and based on the constraint defined for that particular field, thedb transaction
would rise thedjango.db.utils.IntegrityError
becouse at DB level, that field is not allowed to beNULL
Django docs:
"Field.null : If True, Django will store empty values as NULL in the database. Default is False."