0

In models.py:

class PUser(models.Model):
        phone = models.TextField(blank=True, null=True)
        email = models.TextField()
        txt = models.TextField(blank=True, null=True)

I want to create Multidimensional Array for that.

For now this is what I have in the function in views.py:

def main(request):
    users = []
    for i in range (5):
        for a in range(3):
            users[i][a] = PUser.objects.all()
return render(request, 'main.html', {'users': users})

But I know its not correct, its not working.

How should I edit it?

And how the code in the main.html should be?

I was thinking about something like {{ users[2][3] }} for example. How the code should be? (I have read same questions but was not helpful for me)

1 Answer 1

3

Since PUser.objects.all() returns an array of PUser object, you just have to write :

def main(request):
    users = PUsers.objects.all()
    return render(request, 'main.html', {'users': users})

and in your template, iterate on users array :

{% for user in users %}
    {{ user.phone }}
    {{ user.email }}
    {{ user.txt }}
{% endfor %}

If you wanna print a specific user, you can by specifying its index :

{{ users[3].phone }}
{{ users[3].email }}
{{ users[3].txt }}
# or
{{ users.3.phone }}
{{ users.3.email }}
{{ users.3.txt }}
Sign up to request clarification or add additional context in comments.

7 Comments

But as I noticed I want to use something like {{ users[2][3] }}. I want to choose the index I want and put it in different places in my file code. I dont want to print all of them one after an other in a certain place, so dont want to use "for loop". I want to be able to select which index be printed in which place in the code.
I add an example to print a specific user :)
By using {{ users[3].phone }} I faced with this error: Could not parse the remainder: '[3].phone' from 'user[3].phone'
use users[3] variable and not user[3]
try with users.3.phone, do you use django template or jinja?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.