1

How to link more than one django model to the authenticated user of a django app .And how will my view.py and html template look like if i want to display information from these models which are link to the user . Thanks in Advance .

Here is my code as follows

class UserProfile(models.Model):
     user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofile")
     experience= model.TextField(max_Length=500,null=True,blank=False)
     def __str__(self):
         return self.user.username
@receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
     if created:
        UserProfile.objects.create(user=instance)
post_save.connect(create_profile,sender=User)

Now the second model which is where i have a problem

class UserProfileDp(models.Model):
  user = models.OneToOneField(User,on_delete=models.CASCADE,related_name="userprofiledp")
  profile_dp = models.ImageField(upload_to="profile_image" ,null= True,blank=True)
   def __str__(self):
       return self.profile_dp
@receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
if created:
    UserProfileDp.objects.create(user=instance)
post_save.connect(create_profile,sender=User)

The form view of the first model works pretty good without any problem .but i get an error in creating form view for the second model Here is my view.py code for the second model

def user_profile_pic(request):
if request.method == 'POST':

    profile_form = User_dp_form(request.POST,request.FILES,instance=request.user.userprofiledp)
    if  profile_form.is_valid():

        profile_form.save()
        messages.success(request,'Your Profile has been Updated')
        return redirect('success:profile_account')
    else:
        messages.error(request,'fill out the fields correctly')
else:

     profile_form = ProfileForm(instance=request.user.userprofiledp)
return render(request,"success/user_account/edit_profile.html",{'profile_form':profile_form})

Error

RelatedObjectDoesNotExist at /user_profile_pic/

User has no userprofiledp.

1 Answer 1

1

The same way you link one. Don't overthink it.

Both need a OneToOneField to the user and a related name. There's nothing special in the view and html either. You just reference them both from the user model, the same way you reference fields from one profile model.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.