django NOT NULL约束失败错误

时间:2017-12-04 09:41:27

标签: django django-models django-forms django-views

我的格式为django.db.utils.IntegrityError:NOT NULL约束失败:

在我的应用程序中,我要求用户创建一个新项目,然后通过表单询问添加团队成员名称mail.if邮件已存在于数据库中,用户通过邮件邀请用户登录该应用程序邮件不在数据库中,用户通过邮件要求登录。然后邀请的成员被添加到团队中。

尝试在数据库中分配现有用户时出现错误

这是我的代码:

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)

团队模型:

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

项目模型:

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')

任何想法如何解决该错误并将用户添加到团队? 你好;)

回溯:

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

1 个答案:

答案 0 :(得分:2)

您正尝试将未保存的MyUser实例添加到manytomany字段中。您必须获取对象而不是创建新对象。

user = MyUser.objects.get(email=mail)
a4.members.add(user)