我可以将我的文件保存到我告诉它的磁盘,但无法将它保存到实例中,我一点也不知道为什么!
模型.py
class Song(models.Model):
name = models.CharField(max_length=50)
audio_file = models.FileField(upload_to='uploaded/music/', blank=True)
View .py def create_song(request, band_id):
if request.method == 'POST':
band = Band.objects.get(id=band_id)
form = SongForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['audio_file'])
form.save()
return HttpResponseRedirect(band.get_absolute_url)
else:
form = SongForm(initial={'band': band_id})
return render_to_response('shows/song_upload.html', {'form': form}, context_instance=RequestContext(request))
handle_uploaded_file def handle_uploaded_file(f):
ext = os.path.splitext(f.name)[1]
destination = open('media/uploaded/music/name%s' %(ext), 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
song_upload.html(相关部分) {% block main %}
{{band.name}}
<form enctype="multipart/form-data" method="post" action="">{% csrf_token %}
{{ form.as_p}}
<input type="submit" value="Add song" />
</form>
{% endblock %}
表格.py class SongForm(forms.ModelForm):
band = forms.ModelChoiceField(queryset=Band.objects.all(), widget=forms.HiddenInput)
def clean_audio_file(self):
file = self.cleaned_data.get('audio_file',False)
if file:
if file._size > 10*1024*1024:
raise forms.ValidationError("Audio file too large ( > 10mb)")
if not file.content_type in ["audio/mp3", "audio/mp4"]:
raise forms.ValidationError("Content type is not mp3/mp4")
if not os.path.splitext(file.name)[1] in [".mp3", ".mp4"]:
raise forms.ValidationErorr("Doesn't have proper extension")
else:
raise forms.ValidationError("Couldn't read uploaded file")
class Meta:
model = Song
该文件就在媒体/上传/音乐中,但在管理 audio_file 中为空白,如果我为 audio_file 设置了空白 = False(这是我想要做的),我会被告知此字段是必需的。是什么赋予了??提前致谢!已经在这个地方呆了一段时间了,文档对我来说似乎很轻(新手)。
最佳答案
clean_audio_file
应返回此特定字段的清理数据,因此您需要向其中添加 return file
!
来自 django's documentation :
关于django - 为什么我的文件不能保存到实例(它保存到磁盘...)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6479492/