django.db.utils.IntegrityError:NOT NULL约束失败

时间:2017-07-06 10:36:51

标签: python django user-registration

我正在尝试为我的网站构建自定义注册,因此我使用注册配置文件模型。

回溯:

Traceback (most recent call last):
File "C:\Python36\lib\site-packages\django\core\handlers\exception.py", line 
 41, in inner
 response = get_response(request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 187, 
 in _get_response
 response = self.process_exception_by_middleware(e, request)
File "C:\Python36\lib\site-packages\django\core\handlers\base.py", line 185, 
 in _get_response
 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\admin\Desktop\dev1\mysite\mysite\core\views.py", line 74, in 
 complete_profile
 form.save()
File "C:\Python36\lib\site-packages\django\forms\models.py", line 451, in 
 save
 self.instance.save()
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 806, in 
 save
force_update=force_update, update_fields=update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 836, in 
 save_base
 updated = self._save_table(raw, cls, force_insert, force_update, using, 
 update_fields)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 922, in    
 _save_table
 result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Python36\lib\site-packages\django\db\models\base.py", line 961, in 
 _do_insert
 using=using, raw=raw)
File "C:\Python36\lib\site-packages\django\db\models\manager.py", line 85, 
 in manager_method
 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python36\lib\site-packages\django\db\models\query.py", line 1060, 
 in _insert
 return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Python36\lib\site-packages\django\db\models\sql\compiler.py", line 
 1099, in execute_sql
 cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 80, 
 in execute
 return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65, 
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\utils.py", line 94, in 
 __exit__
 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Python36\lib\site-packages\django\utils\six.py", line 685, in 
 reraise
 raise value.with_traceback(tb)
File "C:\Python36\lib\site-packages\django\db\backends\utils.py", line 65, 
 in execute
 return self.cursor.execute(sql, params)
File "C:\Python36\lib\site-packages\django\db\backends\sqlite3\base.py",   
 line 328, in execute
 return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: 
core_profile.user_id

我提交了一份表单后发现了这个错误,该表单是用户在SignUp的电子邮件确认后立即让用户填写个人资料信息。 请看这个图screenshots from the navigator

我的一些代码:

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  birth_date = models.DateField(null=True, blank=True)
  birth_place = models.CharField(max_length=80, verbose_name= ("Lieu de 
    Naissance"))
  email_confirmed = models.BooleanField(default=False)
  adress = models.CharField(max_length=80, verbose_name=("Adresse"))
  adress_complement = models.CharField(max_length=80, verbose_name=
    ("Complément d'Adresse"))
  city = models.CharField(max_length=80, verbose_name=("Ville"))
  zip_code = models.IntegerField(null=True, blank=True)
  drive_licence_num = models.CharField(max_length=80, verbose_name=("N° du 
     Permis de conduire"))
  social_secu_num = models.IntegerField(null=True, blank=True)
  phone_number = models.IntegerField(null=True, blank=True)

  @receiver(post_save, sender=User)
  def update_user_profile(sender, instance, created, **kwargs):
     if created:
     Profile.objects.create(user=instance)
     instance.profile.save()

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from mysite.core.models import Profile

class SignUpForm(UserCreationForm):
  email = forms.EmailField(max_length=254, help_text='Required. Inform a 
          valid email address.')
  class Meta:
      model = User
      fields = ('first_name', 'last_name', 'email', 'username', 'password1', 
                'password2',)

class ProfileForm(forms.ModelForm):
  class Meta:
    model = Profile
    fields = ('birth_date','birth_place', 'adress', 'adress_complement',
              'city', 'zip_code', 'drive_licence_num', 'social_secu_num', 
              'phone_number')

views.py(complete_profile view)

def complete_profile(request):
  #if email_confirmed == True:
  if request.user.is_authenticated():
      if request.method == 'POST':

          form = ProfileForm(request.POST)
          if form.is_valid():
              form.save()

              return render(request, 'home.html')
      else:
          form = ProfileForm()
          return render(request, 'complete_profile.html', {'form': form})
  else:
      return render(request, 'login.html')

2 个答案:

答案 0 :(得分:2)

form = ProfileForm(request.POST,instance=request.user.profile)
          if form.is_valid():
              form.save()

试试这个

答案 1 :(得分:2)

您可能需要将实例request.user.profile传递给表单。

def complete_profile(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = ProfileForm(request.POST, instance=request.user.profile)
            if form.is_valid():
                #form.instance.user = request.user
                form.save()
            return render(request, 'home.html')
        else:
            form = ProfileForm()
            return render(request, 'complete_profile.html', {'form': form})
    else:
        return render(request, 'login.html')