NbaRo
NbaRo

Reputation: 83

Django how go get all products for the logged in user only?

i have the following code, and when the page is displayed the table shows all products for all users no matter which user is logged in. I want to show in the table only the products that was created by the logged in user only, not from all users. Any help with my issue ? Thank you in advance.

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

In the html template:

      <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>

Upvotes: 0

Views: 578

Answers (2)

Ambitions
Ambitions

Reputation: 2581

views.py:

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

HTML template:

<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>

Upvotes: 1

Charnel
Charnel

Reputation: 4432

If your products have foreign key to user, then as easy as:

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

And in templates change transactions loop to:

{% for transaction in transactions %}

Here now you'll have all products for currently logged in user.

Upvotes: 1

Related Questions