尝试创建文件路径时出现以下错误
filepath = '{comp}/utils/locndb/{vehdir}.{filename}'.format(comp,vehdir, filename)
KeyError: 'comp'
我不知道如何从一对多的外键字段中提取字符串
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" and request.FILES['locndb']:
pks = request.POST.getlist("update")
selected_objects = Vehicle.objects.filter(pk__in=pks)
vlist = []
for i 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 your models here.
class UserProfile(models.Model):
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User)
# The additional attributes we wish to include.
compName = models.CharField(max_length = 20)
milkco = models.IntegerField()
# Override the __unicode__() method to return out something 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
我想将文件导入并保存到文件路径/optiload/{customer}/utils/locndb/{vehicle}/{filename}
有没有比我目前更好的方法呢?
答案 0 :(得分:1)
问题是你的字符串包含命名参数(例如{comp}
),但是当你调用format()
时你正在使用位置参数
您可以从字符串中的大括号中删除名称:
filepath = '{}/utils/locndb/{}.{}'.format(comp, vehdir, filename)
或在调用format时使用关键字参数:
filepath = '{comp}/utils/locndb/{vehdir}.{filename}'.format(comp=comp, vehdir=vehdir, filename=filename)