问题
I'm try to make Sign Up form With Profile Model and I will make some changes in the model.
All tables are created when I run manage.py makemigrations
but when I want to run manage.py migrate then is show this error:
django.db.utils.IntegrityError: NOT NULL constraint failed: user_profile.user_id
Model.py
class Profile(models.Model):
user = models.OneToOneField(User,default="", on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(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()
Views.py:
def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user.refresh_from_db()
user.profile.birth_date = form.cleaned_data.get('birth_date')
raw_password = form.cleaned_data.get('password1')
user.save()
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form': form})
form.py:
class SignUpForm(UserCreationForm):
birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD')
class Meta:
model = User
fields = ('username', 'birth_date', 'password1', 'password2', )
回答1:
You cannot have default=""
in foreign key as it is not User id, also foreign keys is not set to be NULL-able. This is why foreign key constraint fails.
user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE)
来源:https://stackoverflow.com/questions/49296083/not-null-constraint-failed-user-profile-user-id