pkdkk
pkdkk

Reputation: 3963

Python how to use POST variable as object parameter

How can I do this:

reader = csv.reader(open(file_path, 'rb').read().splitlines(), delimiter=";")
p = Product()

for key, row in enumerate(reader):
    f = request.POST.get('select_%s' % key) // ex. productname
    p.f = row[key] // HOW TO?, p.f should be "productname" from the variable

Hope you can helt me!

Upvotes: 0

Views: 70

Answers (1)

Steve Mayne
Steve Mayne

Reputation: 22818

Use setattr to set an attribute of an object based on a name at runtime:

reader = csv.reader(open(file_path, 'rb').read().splitlines(), delimiter=";")
p = Product()

for key, row in enumerate(reader):
    f = request.POST.get('select_%s' % key) // ex. productname
    // p.f should be "productname" from the variable
    setattr(p, f, row[key]) 

Upvotes: 2

Related Questions