简体   繁体   English

如何在Django模板中使用objects.filter(user = request.user)?

[英]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. 我使用了PurchaseInfo.objects.filter(user=request.user).values()并希望在模板中显示结果。 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 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 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 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? 我怎么解决这个问题?

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 . 在您的模型中,用户模型的外键关系是purchase_id但在视图中,您尝试按user进行过滤。 You need to filter by purchase_id . 您需要按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. 调试是一项很好的技能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM