2016-11-08 67 views
0

我越來越想創建一個文件路徑Django的KeyError異常試圖格式化外鍵

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}有沒有更好的辦法做到這一點比我如何我目前?

回答

1

的問題是,你的字符串包含命名的參數(如{comp}),但使用的是位置參數,當你調用format()

您可以從您的字符串中的括號去掉名稱:

filepath = '{}/utils/locndb/{}.{}'.format(comp, vehdir, filename) 

或調用格式時使用關鍵字參數:

filepath = '{comp}/utils/locndb/{vehdir}.{filename}'.format(comp=comp, vehdir=vehdir, filename=filename) 
+0

我應該看到...感謝芽 – Jim