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
}
CodePudding user response:
You need to delete the last few migrations, you can do all except the 0001_initial.py
. Then just go and do python manage.py makemigrations your_app_name
and then python manage.py migrate
and it should be solved
CodePudding user response:
You 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 your Profile
model, if you don't specify the constraint null=True
, by default it would be False
so it is saying that you are obliged to give a value (!= to an empty string), so:
if you are doing something like this:
def home_view(request):
context ={}
form = ProfileForm(request.POST)
if form.is_valid():
form.save()
context['form']= form
return render(request, "home.html", context)
When the the form class receives the request
if the name
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 the default='None'
and then is going to pass it to the create
method in the form, and based on the constraint defined for that particular field, the db transaction
would rise the django.db.utils.IntegrityError
becouse at DB level, that field is not allowed to be NULL
Django docs:
"Field.null : If True, Django will store empty values as NULL in the database. Default is False."