rohan
rohan

Reputation: 71

Display record from database to template

Hi i am building a project where there is a form which login user submits , so the user can submit the form multiple times i have used ForeignKey . Now i am struggling to display all the records associated with the user . for example : user 'abc' has fill form and he comes again and fill form so i want to show both the form details of user abc in my template , I am missing something as new to django

views.py

def PostTest(request):
    if request.method == 'POST':
        test = UserTest()
        test.user = request.user
        test.name = request.POST['name']
        test.email = request.POST['email']
        test.location = request.POST['location']
        test.time = request.POST['time']
        test.save()
        return render(request, 'posts/test.html')
test.html
{{ user.usertest.location }}
models.py
class UserTest(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    email = models.EmailField()
    location = models.CharField(max_length=255)
    time = models.IntegerField()
    test_submitted = models.BooleanField()

so i want to get the location filed in my template as user fill multiple times the form so i want all the location of that user in my django template , something looping may work but as newbie don't know how to use it.

Upvotes: 0

Views: 408

Answers (2)

ruddra
ruddra

Reputation: 51988

If there is a ForeignKey relation between UserTest and User, like this:

class UserTest(models.Model)
    user = models.ForeignKey(User)

Then you can simply get the location data like this:

{% for ut in user.usertest_set.all %}
    {{ ut.location }}
{% endfor %}

I am using reverse relation between User and UserTest model to make this query.

Upvotes: 1

S.Kumar
S.Kumar

Reputation: 51

You need to iterate over all the forms saved by the user, so either send them from the views.py file in context in render or get them in the template itself

def PostTest(request):

if request.method == 'POST':
        test = UserTest()
        test.user = request.user
        test.name = request.POST['name']
        test.email = request.POST['email']
        test.location = request.POST['location']
        test.time = request.POST['time']
        test.save()
        submitted_form = UserTest.objects.filter(user=request.user)
        return render(request, context={'forms': submitted_form}, 'posts/test.html')

in html file

{% for form in forms %}
{{ form.location }}
{% endfor %}

Go through the doc for Django for better understanding

Upvotes: 0

Related Questions