我可以讓我的文件保存到磁盤,我告訴它,但不能讓它保存到實例,我沒有絲毫的想法爲什麼!爲什麼我的文件不能保存到實例(它保存到磁盤...)?
models.pyclass Song(models.Model):
name = models.CharField(max_length=50)
audio_file = models.FileField(upload_to='uploaded/music/', blank=True)
views.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
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 %}
forms.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,我被告知這個字段是必需的。是什麼賦予了??
在此先感謝!在這一段時間裏,文檔對我來說似乎很輕鬆(newb)。
您還應該包含'SongForm'的代碼! –
是的,沒有SongForm,我們不能說出發生了什麼。包括 – Brandon
,我的壞! –