0

I have a Django auction project (CS50 course assignment) and I have the following function in views.py:

def show_item(request, items):
items = Listing.objects.filter(item = items)

for item in items:
    ends = item.date + timedelta(days=7)
return render(request, "auctions/show_item.html",{
     "items":items, "ends": ends
    })

This allows me to display the item and its end date. My question is, since there is only one iteration in the loop (I'm showing a single item for auction on the template view), isn't there a cleaner way of doing

ends = item.date + timedelta(days=7) ?

(i.e. just need to obtain the item date field in the model) Without the need of the for loop? I tried : ends = items.date + timedelta(days=7)

but get an error?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Russell
  • 99
  • 7
  • What's the error you're getting – marcusshep Feb 08 '21 at 18:14
  • Please fix the indentation – ominug Feb 08 '21 at 18:16
  • You're going to want to look at Python's `next` method, it's often used to find the first element that meet a criteria. You're also overwritting your original `items` parameter. I'd suggest renaming these variables to be more verbose.https://stackoverflow.com/questions/2361426/get-the-first-item-from-an-iterable-that-matches-a-condition – marcusshep Feb 08 '21 at 18:18
  • I get: auctions.models.User.DoesNotExist: User matching query does not exist. (in the console) – Russell Feb 08 '21 at 18:20
  • I'll look at the next method, thanks. @ominug: Where is the indentation wrong? – Russell Feb 08 '21 at 18:21
  • The body of a function must be indented. We cannot see if the for loop belongs to `show_item`. – ominug Feb 08 '21 at 18:23

1 Answers1

2

You can reference the first item with [0]:

ends = items[0].date + timedelta(days=7)
JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
  • I would insert a condition before which checks the lengths of the array: `if len(items) != 1: raise RuntimeException("not exactly one element retrieved")` – ominug Feb 08 '21 at 18:26