djangodjango-comments

Django comments custom user profile avatar


I'm using Ajax Comments System to render comments and the form and I have a custom user profile that include avatar field

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, default="")
    avatar = ImageField('userprofile', default='avatars/default.png', upload_to="avatars" )

In a regular view i used to do:

from Profiles.models import UserProfile as Author
def BlogPost(request, slug):
    post_slug = posts.objects.get(slug=slug)
    author_avatar = Author.objects.get(user=User.objects.get(username=post_slug.author).id).avatar.url
    args = {
        'post_slug': post_slug,
        'author_avatar': author_avatar,
        'related': _related(post_slug.tags),
    }

    return render(request, "blog_post.html", args)

But Now I'm stack on getting every commentator avatar ... I need solution even if I used to modify the package or override it


Solution

  • For the first time I was trying to override the views and adding some context but later I realized that the template args are in a template tag file some I copied the file into my project and I created a new tag that return the avatar

    @register.simple_tag
    def get_avatar(Profile, comment):
        return Profile.__class__.objects.get(user=comment.user.id).avatar.url 
    # {% get_avatar UserProfile comment %}
    

    I totally missed that template tags folder that's why it took me a while to solve it Update i met some manager and attribution errors this is my final custom tag if anyone have another solution post it

    @register.simple_tag
    def get_avatar(Profile, comment):
            user_id = comment.user.id
            try:
                return Profile.__class__.objects.get(user=user_id).user.avatar.url
            except:
                try:
                    return Profile.objects.get(user=user_id).user.avatar.url
                except AttributeError:
                    return UserProfile.objects.get(user=user_id).avatar.url
    

    put this as hidden input before the avatar tag in your template to avoid referrer ajax server error ( for me this return the slug and for some reason without it the user avatar url will be sent as referrer )

    @register.simple_tag
    def get_url(comment):
        return str(comment.content_object).replace(' ', '_')