我正在尝试将文件保存到从我的应用程序创建的文件夹中,但该文件始终保存在文件夹之外。
我认为:
@login_required(login_url='/sn/login/')
def upload_file(request, folder_id=None):
user = UserProfile.objects.get_profile_user(request.user.email)
store, created = UserStore.objects.get_or_create(user=user)
if folder_id is not None:
parent_folder = UserFolder.objects.get_parent_folder(store, folder_id)
else:
parent_folder = None
if request.method == 'POST':
form = UploadFileForm(user, request.POST, request.FILES)
if form.is_valid():
form.save(parent_folder)
if not parent_folder:
return HttpResponseRedirect(reverse('store_view'))
else:
return HttpResponseRedirect(reverse('folder_view', args=(folder_id,)))
else:
form = UploadFileForm(user)
return render_to_response('quaba/storage/upload_file.html',
{'form': form, 'folder': parent_folder},
context_instance=RequestContext(request))
urls.py
url(r'^quaba/main/storage/upload_file/$',
'upload_file',
name='upload_file'),
url(r'^quaba/main/storage/folder/(?P<folder_id>[\d]+)/upload_file/$',
'upload_file',
name='upload_file_in_folder')
并且forms.py
class UploadFileForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(UploadFileForm, self).__init__(*args, **kwargs)
self.fields['file'] = forms.FileField(label='...')
self.user = user
self.store = UserStore.objects.get(user=user)
def clean_file(self):
total_size = 0
all_files = UserFile.objects.all_files(self.store)
if all_files:
for fi in all_files:
total_size = total_size+fi.file.size
all_folders = UserFolder.objects.all_folders(self.store)
if all_folders:
for fo in all_folders:
total_size = total_size + fo.get_folder_size()
MAX_SIZE = 15728640 #12 MB
content = self.cleaned_data['file']
if content._size > MAX_SIZE:
raise ValidationError('...')
STORE_MAX = 5368709120 #5 GB
if total_size+content._size > STORE_MAX:
raise ValidationError('...')
return content
def save(self, folder):
if folder:
userfile = UserFile(store=self.store,
file=self.cleaned_data['file'],
creator=self.user,
parent_folder=folder)
else:
userfile = UserFile(store=self.store,
file=self.cleaned_data['file'],
creator=self.user)
userfile.save()
return userfile
可选参数folder_id总是None,我不知道为什么。有人可以帮帮我吗?