Home > Software engineering >  Get all values from queryset using templates
Get all values from queryset using templates

Time:09-29

I am trying to retrieve all the queryset data (names and amount) using templates.

views.py

def get_expense(request):
    #expenses = list(Expense.objects.values())
    expenses = Expense.objects.values('name' , 'amount')
    
    if request.method == 'POST':
        form = ExpenseForm(request.POST, request.FILES)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()

            #print(driver_text)
            print(type(expenses))
            return render(request, 'thanks.html', {'expenses':expenses}) #JsonResponse(expenses, safe=False) #

    else:
        form = ExpenseForm()
    return render(request, 'index.html',{'form':form})  

thanks.html:

{{ expenses }}

I am trying to get all those queryset data listed but instead I am getting:

<QuerySet [{'name': 'Home Rent', 'amount': 8000.0}, {'name': 'hjvhjvhv', 'amount': 73.0}, {'name': 'tes', 'amount': 23.0}, {'name': 'dddd', 'amount': 34.0}, {'name': 'qqqqqqqq', 'amount': 56.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 34.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'hjvhjvhv', 'amount': 67.0}, '...(remaining elements truncated)...']>

I need only the name and amount listed instead of the whole queryset.

CodePudding user response:

In your .html file, loop through expenses like this :

{% for expense in expenses %}
<div>
name: {{ expense.name }}, amount: {{ expense.amount }}
</div>    
{% endfor %}
  • Related