Search code examples
djangodjango-modelsdjango-templatesdjango-usersdjango-database

Display Item requested by user in template (django)


I have a simple borrowing items request app, which the user would log in and fill out a form with the following:

  • Item
  • Location
  • Start date
  • End date

This is stored in a database Record stored in database

Then I have a return page where the user will confirm that has returned the item by just clicking return.

I want to show the only the related items with the user logged in to the page, (so just the request the user made: the current item and the previous ones.)

I have the following model for the Request Table:

class Request(models.Model):
       shootkit_id = models.ForeignKey(Shootkit, on_delete=models.CASCADE)
       username = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
       request_start_date = models.DateField('Start Date')
       request_end_date = models.DateField('End Date')
       location = models.ForeignKey(Location, on_delete=models.CASCADE)
  

The following def in views:

def return_form(request):
    form = shootkitForm
    request_db = Request.objects.all
    return render(request, 'return_form.html', {'form':form, 'request_db':request_db})

And the following on the template return:

{% for shootkit in request_db %}
        <div class="callout-info">Hi {{ user }}, you currently have the {{ shootkit.shootkit_id }}</div>
        {% endfor %}

Obviously this is showing every single record on the table (if I ahve more that one record). I would like to only display the item (in this case a shootkit #5) linked with the user User log in info and name of the item

This is my first development ever and is the first time around using django... So that's the only way I can think how to show the records... but I don't know how to link it with the user and show only the record that the user (logged in) appears in. Can anyone help please?

Thank you.


Solution

  • You have to use filter():

    def return_form(request):
        form = shootkitForm
        request_db = Request.objects.filter(username=request.user)
        return render(request, 'return_form.html', {'form':form, 'request_db':request_db})