简体   繁体   中英

How to make this function work in views.py of django?

I want to make this Destination() function work with multiple variables because I don't want to write it again and again. I made it equal with two variables but it is not working. How to solve this problem?

def index(request):
    a,b = Destination()
    a.desc = 'Hello, How are you!'
    a.img = '01.jpg'

    b.desc = 'Hello, How are you!'
    b.img = '02.jpg'

    target = [a,b]

    context = {
     'target': target
    }
    return render(request, 'index.html', context)

If you write a, b = ... you perform iterable unpacking [PEP-3132] . Since a Destination object is likely not iterable, that will not work.

You can use list comprehension for example to generate two Destination s here, this will even skip the need of assigning target = [a, b] a second time:

def index(request):
     = a, b = Destination() 
    a.desc = 'Hello, How are you!'
    a.img = '01.jpg'

    b.desc = 'Hello, How are you!'
    b.img = '02.jpg'

    context = {
     'target': target
    }
    return render(request, 'index.html', context)

and given the desc is a parameter of the constructor of Destination(..) , you can omit that as well:

def index(request):
    target = a, b = [Destination() for __ in range(2)]
    a.img = '01.jpg'
    b.img = '02.jpg'

    context = {
     'target': target
    }
    return render(request, 'index.html', context)

Stricly speaking, you could make some sort of generator, like:

def generator(f, n, *args, **kwargs):
    return [f(*args, **kwargs) for __ in range(n)]

Then the above can be substituted with:

def index(request):
    target = a, b = Destination, 2, desc='Hello, How are you!'
    a.img = '01.jpg'
    b.img = '02.jpg'

    context = {
     'target': target
    }
    return render(request, 'index.html', context)

This thus slightly reduces the amount of boilerplate code, although it might make it less readable, since now the reader will need to inspect the generator function first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM