所以我正在遵循本指南:https://www.youtube.com/watch?v=_sWgionzDoM,到目前为止大约 55 分钟
我的登录内容全部正常工作,但是我无法让仪表板显示数据库中的数据。该表确实在管理页面上显示了数据,但是当我转到用户的仪表板时,它没有显示。
这是我的仪表板代码。
{% extends 'page.html' %}
{% block content %}
{% if messages %}
<div class="row mt-3">
{% for message in messages %}
{% if message.tags == 'error' %}
<div class="col-md-10 col-12 mx-auto alert alert-danger">
{{ message }}
</div>
{% else %}
<div class="col-md-10 col-12 mx-auto alert alert-success">
{{ message }}
</div>
{% endif %}
{% endfor %}
</div>
{% endif %}
<div class="row">
<div class="col-md-10 col-12 mx-auto mt-5">
<div class="d-flex justify-content-end">
<a href="{% url 'main' %}" class="btn btn-primary">+</a>
</div>
<table class="table table-hover table-striped">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Qty</th>
<th scope="col">Category</th>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
{% if items|length == 0 %}
<tr>
<th scope="row">-</th>
<td>no data</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td></td>
</tr>
{% endif %}
{% for item in items %}
<tr>
<th scope="row">{{ item.id }}</th>
<td>{{ item.name }}</td>
{% if item.id in low_inventory_ids %}
<td class="text-danger">{{ item.quantity }}</td>
{% else %}
<td class="text-success">{{ item.quantity }}</td>
{% endif %}
<td>{{ item.category.name }}</td>
<td><a href="{% url 'edit-item' item.id %}" class="btn btn-outline-secondary">Edit</a></td>
<td><a href="{% url 'delete-item' item.id %}" class="btn btn-secondary">Delete</a></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock content %}
这是我的模型的代码
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class InventoryItem(models.Model):
name = models.CharField(max_length=200)
quantity = models.IntegerField()
category = models.ForeignKey("Category", on_delete=models.SET_NULL, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE,)
#related_name='accounts_inventoryitems
def __str__(self):
return self.name
class Category(models.Model):
name = models.CharField(max_length=200)
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name`
这是我的views.py 文件
class Dashboard(View):
def get(self, request):
items = InventoryItem.objects.filter(user=self.request.user.id).order_by('id')
return render(request, 'dashboard.html', {'items': items})
我真的不确定在哪一点它不再发送数据。我进行了调试,这表明数据库填充了正确的值。
希望你能帮忙!
问题出在你的queryset。
线路:
filter(user=request.user.id)
筛选用户对象的库存模型,但您要筛选的值是当前用户的主键,而不是用户对象本身。
要解决此问题,您需要将过滤器值更改为用户实例:
InventoryItem.objects.filter(user=request.user)
或者,您可以直接过滤user_id
:
InventoryItem.objects.filter(user_id=request.user.id)