Django how to connect user profile model with comment model for showing data from user profile?

I want to show user profile picture publicly in my blog comment section. I tried to use foreignkey in my comment model for connect user profile model then use this in my html for showing profile picture but didn’t work.

 <img src="{{blogcomment.userprofile.profile_pic.url}}"> #didn't show any profile picture until I manually go to admin panel and set foreignkey of userprofile in my blogcomment model.

here is my full code:

userprofile model

class UserProfile(models.Model):
      user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")
      slug = models.SlugField(max_length=2000,unique=True,blank=True,null=True)
     
      profile_pic = models.ImageField(upload_to='profile/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True)

blogcomment model:

class BlogComment(models.Model):
       blog = models.ForeignKey(Blog,on_delete=models.CASCADE,null=True, blank=True,related_name="blogcomment_blog")
       comment = models.TextField(max_length=50000)
       name = models.CharField(max_length=250)
       userprofile= models.ForeignKey(UserProfile,on_delete=models.CASCADE,null=True,blank=True)
       user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='user_comment',blank=True,null=True)

views.py:

   if comment_form.is_valid():
                isinstance = comment_form.save(commit=False)
                isinstance.user = request.user
                isinstance.blog = blog
                isinstance.save()

You don’t need a separate reference to the userprofile, assuming there’s a direct link (foreign key) from the user to the user profile.

You’re already populating the user attribute, so blogcomment.user.userprofile.profile_pic.url should be adequate for accessing that attribute.

KenWhitesell I tried as you mentioned but didn’t work blogcomment.user.userprofile.profile_pic.url until I use this {{blogcomment.userprofile.profile_pic}} and manually go to admin panel and save the foreignkey of usermodel.

KenWhitesell I think I need to be save foreignkey of userprofile when any comment will be created but don’t understand how to identify right profile and save it with comment model. Why {{blogcomment.user.userprofile.profile_pic}} not rendering in my template?? It should be work as I using user as a foreignky but why it’s not rendering? When I use this {{blogcomment.user.userprofile}} then seeing this in my template


members.UserProfile.None But I have user profile pic and others data for admin user.

The implications of what you’re saying then is that the user profile object is not being created properly with the right reference to the user object.

1 Like

KenWhitesell I added an extra fields in my forms which is user userprofile and save this user profile with commnet. then using this in my template
<img src="{{ blogcomment.userprofile.profile_pic .url }}" >
for showing profile picture and it’s showing the profile pic of user.

My question is why this not working '{{blogcomment.user.userprofile.profile_pic}}` ? where user is a foreignkey in my model.

here I am adding froms.py code which help you to identify why '{{blogcomment.user.userprofile.profile_pic}}` not working?

class CommentFrom(forms.ModelForm):
      captcha = CaptchaField()
      class Meta:
          model = BlogComment
          fields = ['name','email','comment','parent','sno','blog','user','userprofile']

This queryset {{ blogcomment.userprofile.profile_pic .url }} working but why this not working '{{blogcomment.user.userprofile.profile_pic}}`???

The problem most likely is not here. Everything you’ve posted implies that the real problem is in the creation of your userprofile object.

I would need to see the code that creates the userprofile object.

class UserProfile(models.Model):

      user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")

      slug = models.SlugField(max_length=2000,unique=True,blank=True,null=True)

      profile_pic = models.ImageField(upload_to='profile/images/',validators=[validate_file_size,FileExtensionValidator( ['png','jpg'] )],blank=True,null=True)
      #my others fields

class MyCustomer(models.Model):
      user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True)
      email = models.EmailField(max_length=1000) 

I have others model like MyCustomer. When any user signup as customer, author or subscriber an user profile object creating and I am using signals for create profile objects.

#customer_signals
@receiver(post_save, sender=MyCustomer)
def user_is_created_or_save(sender,instance,created,**kwargs):
#.....others code
if created:
        UserProfile.objects.create(user=user)

That’s a start, but not the complete code. I still can’t follow what all is happening from only this.

here is my forms.py

class CustomerSignUpForm(UserCreationForm):

      username = forms.CharField(max_length=100,)

      email = forms.EmailField(max_length=1000)

      first_name = forms.CharField(max_length=200)

      last_name = forms.CharField(max_length=200)

      def clean_email(self):

          email = self.cleaned_data['email']

          if len(email) > 1000:

             raise ValidationError ("maximum 1000 character allowd in email")

          if Subscriber.objects.filter(email=email):

              raise ValidationError ("email alrday exist") 

          return email  

      

      def clean_username(self):

          username = self.cleaned_data['username']

          if len(username) > 100:

             raise ValidationError ("maximum 100 character allowd in username")

          

          if " " in username:

               raise ValidationError("Space not allowed in username")

          return username 

       

      def clean_first_name(self):

          first_name = self.cleaned_data['first_name'] 

          if len(first_name)>200:

             raise ValidationError("maximum 200 character alowed in first name") 

          return first_name

      

      def clean_last_name(self):

          last_name = self.cleaned_data['last_name'] 

          if len(last_name)>200:

             raise ValidationError("maximum 200 character alowed in last name") 

          return last_name

            
            

      class Meta(UserCreationForm.Meta):

        

           model = UserManagement

           

      @transaction.atomic

      def save(self):

        user = super().save(commit=False)

        user.is_customer = True

        user.save()

        MyCustomer.objects.create(

            user=user,

            email=self.cleaned_data.get('email'),

            first_name =self.cleaned_data.get('first_name'),

            last_name =self.cleaned_data.get('last_name'),

            

        )

        my_group = Group.objects.get(name='myclients')

        my_group.user_set.add(user) 

        return user

class ProfileFroms(forms.ModelForm):

      country = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control",'placeholder': 'Your country name'}),max_length=200,required=False)

      mobile = forms.IntegerField(widget=forms.TextInput(attrs={'class': "form-control",'placeholder': 'Your contact naumber'}),required=False)

      website_link = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control",'placeholder': 'Your website address'}),max_length=3000,required=False)

      skype = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control",'placeholder': 'Your skype username'},),max_length=2000,required=False)

      twitter = forms.CharField(widget=forms.TextInput(attrs={'class': "form-control",'placeholder': 'Your twitter profile link'}),max_length=2000,required=False)

      class Meta:

          model = UserProfile

          fields = ["profile_pic","mobile","country","website_link","skype","twitter"]

Where are you assigning the relationship between the UserProfile and the User model?

You have a field in UserProfile:
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")

You still have not shown me any code where you set that field to an instance of AUTH_USER_MODEL. I would be expecting to see that in the save method of your CustomerSignUpForm. (You’re already creating the MyCustomer object at that point, it would make sense to me to create the UserProfile at that same time.)

KenWhitesell
isn’t it an User model user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")???

class UserProfile(models.Model):
      user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")

I have same things in my blog comment model

class BlogComment(models.Mode):
        user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")

I am thinking as user and user have in my two model so I can access via user to userprofile or from userprofile to blog. But I couldn’t.

here is my Abstract user model

class UserManagement(AbstractUser):

      is_blog_author = models.BooleanField(default=False)

      is_editor = models.BooleanField(default=False)

      is_subscriber = models.BooleanField(default=False)

      is_customer = models.BooleanField(default=False)

A ForeignKey field defines the field to be set - it doesn’t set it. (Also, using a ForeignKey in UserProfile allows for multiple profiles to be defined for a User - is that what you want?)

1 Like

yes I am thinking as I have user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) in my blogcommnet model and profile model so I can access both of model via user. But can’t access any of model via user. I needed to set model name as foreignkey like this userprofile= models.ForeignKey(UserProfile,on_delete=models.CASCADE,null=True,blank=True) for access userprofile from blogcommnet model and same will be for blogcommnet if I want to access from userprofile model.

You can access them through the User object if you set those fields to the right User object, and that’s what you’re missing. Yes, you’ve defined the field to hold the relationship. But when you create that object, you need to actually establish the relationship between them. That does not happen “by magic”, you need to make it happen.

1 Like