목표는 사용자가 업로드 한 파일이 사용자에 따라 달라지는 디렉토리 위치에 저장되도록 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.
하지만 사용자 이름은 유효한 문자열입니다. OMG. 나는 이유를 모르지만, 지금은 완전히 작동합니다. 이 질문에 답을 더 잘 표시해주세요. – mgag