1

I don't want to repeat Destination function again and again in separate variables. I tried to make different variables and equaled them to Destination() but it didn't work. How to make a loop in it so that I don't have to repeat it?

def index(request):
    dest1 = Destination()
    dest1.desc = 'Hello, How are you?'
    dest1.img = '01.jpg'

    dest2 = Destination()
    dest2.desc = 'Hello, HOw are you?'
    dest2.img = '02.jpg'

    dests1 = [dest1, dest2] # that was missing.

    context = {
       'dests1': dests1,
       'dests2': dests2,
}

return render(request, 'index.html',context)
2
  • Will anyone answer my question? Commented Jul 11, 2019 at 4:13
  • I have added an answer Commented Jul 11, 2019 at 4:17

2 Answers 2

3

inside your def index(request) function make a loop upto the number of time you needed Destination() object and save data in a list, from that list you can retrieve data later. You can also make list of images, descriptions to things more easily

numberOfDestinationNeeded = 4 # change this number according to your need
destList = []
for i in range(numberOfDestinationNeeded):
    destObj = Destination()
    destObj.desc = "dfsfs"
    destObj.img = '02.jpg'
    destList.append(destObj)
Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this.

no_of_destinations = 4 #Some number.
context = {}
for index in range(1, no_of_destinations+1):
    dest = Destination()
    dest.desc = 'How are you?'
    dest.img = '0{}.jpg'.format(index)
    context['dest{}'.format(index)] = dest

return render(request, 'index.html',context)

2 Comments

Then its a different issue. Check if image is present or not in your static directory.
Images are present. I have edited my code. I missed something in my code. Check and tell me.

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.