Ad

NOT NULL Constraint Failed: Dashboard_profile.user_id

I'm trying to save the last IP of User to the Profile module in Django but I get always NOT NULL constraint failed I know that last_ip should be set tonull=True and I run this commands:py .\manage.py makemigrations and py .\manage.py migrate. if you have any suggestions to save IP to the user that will be helpful for me.

Thanks in advance.

#models.py 

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(blank=True, max_length=150)
    last_ip = models.GenericIPAddressField(null=True, blank=True)
    avatar = ContentTypeRestrictedFileField(max_upload_size=10485760, null=True, verbose_name="",default='default.jpg', blank= True, content_types=['image/png', 'image/jpeg'])
    
    def __str__(self):
        return self.user.username
#forms.py 

class UpdateUserForm(forms.ModelForm):
    username = forms.CharField(max_length=150, required=True)
    first_name = forms.CharField(max_length=150, required=False)
    last_name = forms.CharField(max_length=150, required=False)
    email = forms.EmailField(required=True)
    
    class Meta:
        model = User
        fields = ['username','first_name','last_name','email']

class UpdateAvatarBio(forms.ModelForm):
    avatar = forms.ImageField()
    bio = forms.CharField()
    class Meta:
        model = Profile
        fields = ['avatar', 'last_ip', 'bio']
#views.py
def ip_client(request):
    return (
        x_forwarded_for.split(',')[0]
        if (x_forwarded_for := request.META.get('HTTP_X_FORWARDED_FOR'))
        else request.META.get('REMOTE_ADDR')
    )
def profile(request):
    ip = ip_client(request)
    model = Profile(last_ip=ip)
    model.save() # Traceback suppose here is the issue
    if request.method == 'POST':
    ...
    ...
    return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form})
Ad

Answer

You didn't add the user to Profile before saving it

def profile(request):
    ip = ip_client(request)
    model = Profile(last_ip=ip)
    moddl.user=request.user      #Add this
    model.save() # Traceback suppose here is the issue
    if request.method == 'POST':
         ...
         ...
   return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form})

Edit: Since the user is OneToOne (which means it is a the primary key), so Your code shall be like this

def profile(request):
    ip = ip_client(request)
    profile = Profile.objects.get(user=request.user)
    profile.last_ip = ip
    profile.save()
    if request.method == 'POST':
         ...
         ...
   return render(request, 'profile.html', {'user_form': user_form, 'profile_form': profile_form})
Ad
source: stackoverflow.com
Ad