Reputation: 521
I tried getting the list of objects from the current logged users. There something missing in the codes. I wrote a class-based view as well as function-based views. Class-based views give an error like 1 positional argument but two were given. And in function-based view it giving only first item instead looping through it.
I want to show the pass investments inventory record of each investor.
Thank you!
views.py (Function-Based Views)
def InvestmentListView(request):
investors = Investment.objects.all(id=request.user.id)
args = {'investors':investors}
return render(request, 'investors/myinvest.html', args)
This only retrieving an only first item.
views.py (class-Based viewa)
class InvestmentListView(ListView):
model = Investment
template_name = 'investors/myinvest.html'
context_object_name = 'total_invested_by_user'
def get_queryset(self):
return Investment.objects.filter(investor=self.request.user.id)
This CBV gives an error like 1 positional argument, but 2 were given.
myinvest.html
<div class="container">
{% if user.is_authenticated %}
<h2>Investor Name: {{ request.user }}</h2>
<table>
<tr>
<th>Amount Invested</th>
<th>Date</th>
<th>Rate Of Interest</th>
<th>Return</th>
<th>Profit</th>
</tr>
<tr>
{% for invest in investors %}
<th>{{ invest.amount }}</th>
<th>{{ invest.timestamp }}</th>
<th>{{ invest.rate }}</th>
<th>None</th>
<th>None</th>
{% endfor %}
</tr>
</table>
{% endif %}
Here, models.py
class Investor(models.Model):
name = models.CharField(max_length=99)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Investment(models.Model):
amount = models.FloatField(blank=False)
rate = models.FloatField(blank=False)
timestamp = models.DateField(default=datetime.now)
investor = models.ForeignKey(Investor, on_delete=models.CASCADE)
def __str__(self):
return str(self.investor)
Upvotes: 0
Views: 48
Reputation: 1847
You are filtering the Investment
id with your user id which is not correct. This should work:
investors = Investment.objects.filter(investor__user=request.user)
Upvotes: 1