Django仅如何为登录用户获取所有产品?

问题描述 投票:0回答:2

i具有以下代码,并且在显示页面时,该表将显示所有用户的所有产品,无论哪个用户登录。我只想在表中显示仅由登录用户而非所有用户创建的产品。对我的问题有帮助吗?预先谢谢你。

views.py

@login_required
def eadmin(request):
    transactions = Product.objects
    return render(request, 'accounts/index.html', {'transactions': transactions})

models.py

class Product(models.Model):
    details = models.CharField(max_length=1000)
    opname = models.CharField(max_length=100)
    pub_date = models.DateTimeField()
    amount = models.IntegerField()
    contactemail = models.TextField()
    purpose = models.TextField()
    poster = models.ForeignKey(User, on_delete=models.CASCADE)
    transactionid = models.CharField(max_length=6)

    def __str__(self):
        return self.transactionid

在html模板中:

      <table class="table">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">XXXXX</th>
            <th scope="col">Amount €</th>
            <th scope="col">Transaction ID</th>
          </tr>
        </thead>
        {% for transaction in transactions.all %}
        <tbody>
            <tr>
            <th scope="row">-</th>
            <td>{{ transaction.opname }}</td>
            <td>{{ transaction.amount }}</td>
            <td>{{ transaction.transactionid }}</td>
            </tr>
        </tbody>
       {% endfor %}
      </table>
python django templates authentication username
2个回答
0
投票

如果您的产品具有用户外键,那么简单:

transactions = Product.objects.filter(user=request.user)

并且在模板中将事务循环更改为:

{% for transaction in transactions %}

现在您将拥有当前登录用户的所有产品。


0
投票

views.py:

@login_required
def eadmin(request):
    transactions = Product.objects.filter(poster=request.user)
    return render(request, 'accounts/index.html', {'transactions': transactions})

HTML模板:

<table class="table">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">XXXXX</th>
            <th scope="col">Amount €</th>
            <th scope="col">Transaction ID</th>
          </tr>
        </thead>
        {% for transaction in transactions %}
        <tbody>
            <tr>
            <th scope="row">-</th>
            <td>{{ transaction.opname }}</td>
            <td>{{ transaction.amount }}</td>
            <td>{{ transaction.transactionid }}</td>
            </tr>
        </tbody>
       {% endfor %}
      </table>
© www.soinside.com 2019 - 2024. All rights reserved.