2010-03-07 84 views
1

目標是動態更新upload_to,以便用戶上傳的文件存儲在依賴於用戶的目錄位置中。有幾個在線的例子,但沒有一個使用ModelForm。看到這兩個問題的代碼片段,其中一個是我得到一個空的字符串爲instance.user值,當我嘗試修復它時,表單無效。Django:如何在ModelForm中使用upload_to = function

# models.py 

def get_file_path(instance, filename): 
    # make the filepath include the signed in username 
    print "inst: %s" % instance.__dict__.keys() 
    print "inst:user:%s" % instance.user # <-- This is empty string!! 
    print "file: %s" % filename 
    return "%s/myapp/%s/%s" % (settings.MEDIA_ROOT, instance.user, filename) 

class trimrcUpload(models.Model): 
    user = models.CharField(max_length = 20) 
    inputFile = models.FileField(upload_to = get_file_path) 


# forms. py 

class trimrcUploadForm(ModelForm): 

    class Meta: 
     model = trimrcUpload 
     exclude = ('resultFile', 'numTimesProcessed') 

# views.py 

def myapp_upload(request, username, template_name="myapp/myapptemplate.html"): 

    dummy = trimrcUpload(user=username) 
    if request.POST: 
     form = trimrcUploadForm(request.POST, request.FILES, instance=dummy) 
     if form.is_valid(): 
      success = form.save() 
      success.save() 

    # form is not valid, user is field is "required" 
    # the user field is not displayed in the template by design, 
    # it is to be populated by the view (above). 

# http://docs.djangoproject.com/en/1.0/topics/forms/modelforms/ 
# about halfway down there is a "Note" section describing the use of dummy. 

回答

1

我想象你的問題來自試圖用用戶名填充你的模型的用戶屬性。否則

dummy = trimrcUpload(user=request.user) 

,如果你仍然想在用戶名傳遞就像你現在,你可以嘗試喜歡的東西:如果上傳表單總是會被一個登錄的用戶使用,你可以使用它代替

try: 
    user = User.objects.get(username=username) 
    dummy = trimrcUpload(user=user) 
except User.DoesNotExist: 
    # Probably have to set some kind of form error 

我會推薦與第一個選項,這將允許你不必傳遞用戶名到視圖。

+0

但用戶名是一個有效的字符串。我的天啊。我不知道爲什麼,但現在完全工作。我更好地將其標記爲已回答。 – mgag 2010-03-07 18:58:10

0

問題中的原始代碼實際上起作用。