django.db.utils.IntegrityError: NOT NULL constrain

2019-07-14 02:24发布

问题:

i'm trying to build a customised registration to my site, so i'm using a sign Up with Profile Model.

Traceback:

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

i'm having this ERROR after submit a form that i made to let user complete profile information just after SignUp's email confirmation. Look at this diagram

some of my code:

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

回答1:

You may need to pass instance request.user.profile to the form.

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


回答2:

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

try this