python - Django KeyError when trying to format foreignkey -
i'm getting following error when trying create filepath
filepath = '{comp}/utils/locndb/{vehdir}.{filename}'.format(comp,vehdir, filename) keyerror: 'comp'
i don't know how extract string one-to-many foreignkey field
extra.py
def get_file_path(vehicle, filename): filepath = '' vehdir = vehicle.vehid print vehdir comp = getattr(vehicle.company, 'user', none) print comp filepath = 'optiload/{comp}/utils/locndb/{vehdir}.{filename}'.format(comp,vehdir, filename) print filepath return filepath
views.py
@login_required def loadlocndb(request): if request.method == "post" , request.files['locndb']: pks = request.post.getlist("update") selected_objects = vehicle.objects.filter(pk__in=pks) vlist = [] in selected_objects: vlist.append(i) locnfile = request.files['locndb'] fs = filesystemstorage() filename = fs.save(locnfile.name, locnfile) filename = get_file_path(i, filename) uploaded_file_url = fs.url(filename) return render(request, 'portal/loadlocndb.html',{"vlist":vlist, "uploaded_file_url": uploaded_file_url})
models.py
# create models here. class userprofile(models.model): # line required. links userprofile user model instance. user = models.onetoonefield(user) # additional attributes wish include. compname = models.charfield(max_length = 20) milkco = models.integerfield() # override __unicode__() method return out meaningful! def __unicode__(self): return self.user.username class vehicle(models.model): vehid = models.charfield(max_length = 10) company = models.foreignkey(userprofile, default = 1) #depot = models.foreignkey(depot, default = 1) locndb = models.filefield(upload_to='optload/', default= "setting.media_root/locndb/locndb.csv") class meta: db_table = "vehicle" def __unicode__(self): return self.vehid
i want import , save file filepath /optiload/{customer}/utils/locndb/{vehicle}/{filename}
there better way how currently?
the problem string contains named arguments (e.g. {comp}
), using positional arguments when call format()
you can either remove names braces in string:
filepath = '{}/utils/locndb/{}.{}'.format(comp, vehdir, filename)
or use keyword arguments when calling format:
filepath = '{comp}/utils/locndb/{vehdir}.{filename}'.format(comp=comp, vehdir=vehdir, filename=filename)
Comments
Post a Comment