stin
stin

Reputation: 93

How to use objects.filter(user=request.user) in Django templates?

I used PurchaseInfo.objects.filter(user=request.user).values() and want to show the result in templates. But, I get this error message:

FieldError at /auth/purchaseHistory/


Cannot resolve keyword 'user' into field. Choices are: id, product_name, product_price, purchase_addr, purchase_date, purchase_id, purchase_id_id, purchase_name, purchase_phone

purchaseinfo/models.py

class PurchaseInfo(models.Model):
    purchase_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    purchase_name = models.CharField(max_length=30)
    purchase_addr = models.CharField(max_length=100)
    purchase_phone = models.CharField(max_length=15)
    ...and so on

customlogin/views.py

from purchaseinfo.models import PurchaseInfo
def purchaseHistory(request):
    history = PurchaseInfo.objects.filter(user=request.user).values()
    return render(request,'customlogin/purchaseHistory.html',{'history':history})

purchaseHistory.html

{% for i in history %}
<tr>
    <td>{{i.purchase_id}}</td>
    <td>{{i.purchase_name}}</td>
    <td>{{i.purchase_addr}}</td>
    <td>{{i.purchase_phone}}</td>
    <td>{{i.product_name}}</td>
    <td>{{i.product_price}}</td>
    <td>{{i.purchase_date}}</td>
</tr>
{% endfor %}

How can I solve this problem?

Upvotes: 5

Views: 9835

Answers (1)

Vaibhav Vishal
Vaibhav Vishal

Reputation: 7118

Update your views to this:

history = PurchaseInfo.objects.filter(purchase_id=request.user).values()

In your model the foreign key relation to User model is purchase_id but in views you are trying to filter by user. You need to filter by purchase_id.
Most of time the error messages explain the problem pretty well, try to understand what it's saying and attempt to fix it on your own. Debugging is a nice skill to have.

Upvotes: 7

Related Questions