PhilM
PhilM

Reputation: 361

Show all comments from a specific user in django

I am trying to consolidate all the comments, on various products, from the logged in user in an "Account" page.

My initial plan was to request all comments from the user id.

Because I created a Profile model, I thought the right way to approach this was to link it to the profile id, and not directly to the use id.

Obviously, it's not working.

Am I close to it? or should I think of it completely differently? (new to programming, as you can see on the code)

Starting with my models.py

class ReviewRating(models.Model):
    user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE)
    product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE)
    review=models.TextField(max_length=250)

    def __str__(self):
        return '%s - %s - %s'%(self.user, self.product, self.date_added)

class Profile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    general_reviews = models.ForeignKey(ReviewRating,null=True, on_delete=models.CASCADE)
 

def str(self): return str(self.user)

Views.py

def account(response, profile_id):
    generalreviews_list = Profile.general_reviews.objects.all(pk=profile_id)
    return render(response,"main/account.html", {'generalreviews_list':generalreviews_list})

URLS

path("account/<profile_id>/", views.account, name="account"),

Upvotes: 0

Views: 479

Answers (2)

user19584772
user19584772

Reputation:

Method - 1 (easiest and logical method)

profile.html:

{% for comment in request.user.reviewrating_set.all %}
    {{ comment.review }}
{% endfor %}

Method - 2 (by setting a related_name what Django already defines one called foo_set )

You need to add a related_name attribute to the user field under ReviewRating

class ReviewRating(models.Model):
    user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE, related_name="comments") 

That's It! You can use it on the profile HTML like this:

profile.html:

{% for comment in request.user.comments %}
    {{ comment.review }}
{% endfor %}

Upvotes: 2

Usama Saeed
Usama Saeed

Reputation: 331

The best way is to link it with the main user model in your case it will be best to link it with user_id. After that, you can use the following query to access all the comments made by the currently logged-in user.

Views.py

current_user = request.user
queryset_obj = Model.objects.filter(foreign_key_field_name=current_user)
context = {
   'comments' = quesyset_obj,
}

Templates.py

{% for comment in comments %}
   {{comment.review}}
{% endfor %}

Upvotes: 1

Related Questions