下面是我项目中 django 代码的简化版本;它允许用户上传文件并给它一个标题。此功能完美运行。但是,当用户稍后重新编辑表单时,文件和标题会重新显示,但是当用户提交文件时,文件是空的。重新打开以进行编辑的表单的文件字段如下所示:
目前: media_location/uploadedfile.mp3
更改: [选择文件] 未选择文件
在我提交之后,它是:
- 此文件为必填项
[选择文件] 未选择文件
如何获取它以便用户不必重新上传文件?提交完成后是否将该字段设为只读,或者是否保持可编辑,对我来说并不重要。完成的项目不适用于客户,仅适用于一小部分受信任的用户,但如果可能,我仍然希望遵循最佳实践。谢谢你的帮助。
姜戈代码:
模型.py
class Recording(models.Model):
rec_title=models.CharField(max_length=200,blank=True)
rec_file = models.FileField(upload_to='recordings')
表格.py
from django import forms
from songstorage.models import Recording
class RecordingForm(forms.ModelForm):
rec_file=forms.FileField(label='Upload File')
rec_title=forms.CharField(label='Recording Title',required=False)
class Meta:
model=Recording
视图.py
def addrecordings(request,recordingfile):
#if there is a recordingfile in the url, the user is editing...
if recordingfile:
recording=Recording.objects.get(rec_title=recordingfile)
recording_form = RecordingForm(instance=recording)
#...Otherwise a new form is createing a new one
else:
recording_form = RecordingForm(request.POST, request.FILES)
#When the form is submitted, do the following:
if request.method == 'POST':
#check if its valid
if recording_form.is_valid():
recording_form.save()
#if sucessfully submitted, redirect
return redirect('/recordings/')
return render_to_response('addrecordings.html',{'recording_form':recording_form},context_instance=RequestContext(request))