I am having an error in the form django.db.utils.IntegrityError: NOT NULL constraint failed:
in my app I ask the user to create a new project and then is ask via a form to add team member name mail.if the mail already exist in the database the user is invited to by mail to login to the app if the mail is not in the database the user is asked by mail to sign in. Then the invited member is added to the team.
I am getting that error when trying to assign an existing user in the data base
here is my code :
def TeamRegister2(request):
#import pdb; pdb.set_trace()
InviteFormSet = formset_factory(InviteForm2)
if request.method == 'POST':
formset = InviteFormSet(request.POST)
if(formset.is_valid()):
for i in formset:
mail = i.cleaned_data['Email']
if MyUser.objects.filter(email = mail).exists():
user = MyUser(email = mail)
u1 = user.id # get user ID
a1 = MyUser.objects.get(email = request.user.email) #get user email
a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the user
a3 = a2.latest('id') # extract the last project
a4 = a3.team_id # extract the team linked to the project
a4.members.add(u1) # add the member to the team
invited_user = MyUser.objects.get(email = mail)
current_site = get_current_site(request)
message = render_to_string('acc_join_email.html', {
'user': invited_user.first_name,
'domain':current_site.domain,
})
mail_subject = 'You have been invited to SoftScores.com please LogIn to get access to the app'
to_email = mail
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
else:
user = MyUser(email = mail)
password = MyUser.objects.make_random_password()
user.set_password(password)
user.is_active = False
user.is_employee = True
user.save()
u1 = user.id #get user id
a1 = MyUser.objects.get(email = request.user.email) #get user email
a2 = Project.objects.filter(project_hr_admin = a1) #get all project created by the user
a3 = a2.latest('id') # extract the last project
a4 = a3.team_id # extract the team linked to the project
a4.members.add(u1) # add the member to the team
current_site = get_current_site(request)
message = render_to_string('acc_active_email.html', {
'user':user,
'domain':current_site.domain,
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'token': account_activation_token.make_token(user),
})
mail_subject = 'You have been invited to SoftScores.com please sign in to get access to the app'
to_email = user.email
email = EmailMessage(mail_subject, message, to=[to_email])
email.send()
messages.success(request, 'testouille la fripouille')
return HttpResponseRedirect(reverse('website:ProjectDetails', kwargs={'pk':a3.id}))
else:
print("The entered form is not valid")
else:
formset = InviteFormSet()
return render(request,'team_register.html', {'formset':formset})
MyUser Model:
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=150, blank=True, null=True)
last_name = models.CharField(max_length=150, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_hr = models.BooleanField(default=False)
is_candidate = models.BooleanField(default=False)
is_employee = models.BooleanField(default=False)
company = models.CharField(max_length=100, blank=True, null=True)
Team model:
class Team(models.Model):
team_name = models.CharField(max_length=100, default = '')
team_hr_admin = models.ForeignKey(MyUser, blank=True, null=True)
members = models.ManyToManyField(MyUser, related_name="members")
def __str__(self):
return self.team_name
Project models:
class Project(models.Model):
name = models.CharField(max_length=250)
team_id = models.ForeignKey(Team, blank=True, null=True)
project_hr_admin = models.ForeignKey('registration.MyUser', blank=True, null=True)
candidat_answers = models.ManyToManyField('survey.response')
any idea how to fix that error and add the user to the team ? thx you ;)
traceback:
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
328. return Database.Cursor.execute(self, query, params)
The above exception (NOT NULL constraint failed: website_team_members.myuser_id) was the direct cause of the following exception:
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/raphaelbendenoun/Documents/Django Projects/Authentication_project/registration/views.py" in TeamRegister2
85. a4.members.add(u1) # add the member to the team
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in add
934. self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py" in _add_items
1103. for obj_id in new_ids
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in bulk_create
443. ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _batched_insert
1099. self._insert(item, fields=fields, using=self.db)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/query.py" in _insert
1076. return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
1107. cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
80. return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/utils.py" in __exit__
94. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/utils/six.py" in reraise
685. raise value.with_traceback(tb)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
65. return self.cursor.execute(sql, params)
File "/Users/raphaelbendenoun/anaconda/envs/myDjangoEnv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
328. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /registration/auth_team_register3/
Exception Value: NOT NULL constraint failed: website_team_members.myuser_id