boyenec
boyenec

Reputation: 1617

Django how to automatically save user in a Django Form?

When I am passing "user" fields to my Model forms. I am getting all user details as dropdown. see the picture:

enter image description here

I am trying to save current user instance without showing this dropdown because I want user will be automatically save without selecting or showing this dropdown.

here is my forms.py file:

class ProfileFroms(forms.ModelForm):
      
      class Meta:
          model = UserProfile
          fields = ["user","profile_pic","mobile","country","website_link"] 

when I remove "user" froms fields then getting this error:

"NOT NULL constraint failed: members_userprofile.user_id"

I also tried this code for saving current user but it is getting me the same error.

views.py

if forms.is_valid():
          forms.user = request.user

here is my full code:

models.py

class UserManagement(AbstractUser):
      is_subscriber = models.BooleanField(default=False)
      is_customer = models.BooleanField(default=False)


class UserProfile(models.Model):
      user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")
      profile_pic = models.ImageField(upload_to='profile/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True)
      mobile = models.IntegerField(blank=True,null=True)
      country = models.CharField(max_length=200,blank=True,null=True)
      website_link = models.CharField(max_length=3000,blank=True,null=True)

views.py

def UserProfileView(request):

   userinfo = UserManagement.objects.filter(username=request.user)
    
   
   forms = ProfileFroms(request.POST,request.FILES or None)
   if request.method == "POST":
      if forms.is_valid():
          #forms.user = request.user #tried this line for save current user but didn't work 
          forms.save()
          messages.add_message(request, messages.INFO,'Profile updated sucessfully') 
          return redirect("members:user-profile-private")
   else:
      messages.add_message(request, messages.INFO,'Somethings wrong. Profile not updated')  
      print("invalid")

   context={"userinfo":userinfo,"forms":forms}

   return render(request,"members/privateprofile.html",context)

Upvotes: 2

Views: 701

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

Remove the user field from the form:

class ProfileFroms(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['profile_pic', 'mobile', 'country', 'website_link']

and then you alter the .instance of the form (not the form itself), so:

if forms.is_valid():
    forms.instance.user = request.user
    forms.save()

Upvotes: 2

Related Questions