0
我無法管理上傳和保存帶有文本值的文件作爲描述。我不明白爲什麼:形式和模型顯然有相關的領域。當我從我的視圖中刪除對文本字段tekst
的引用時,它會正確上載並保存該文件。僅供參考:我在模型字段中使用了子目錄結構基礎,這就是爲什麼我的模型中有def get_upload_to
,而我認爲是Overig_Beeld.objects.create
,而不僅僅是upload.save()
。上傳帶有文字描述的文件
型號:
def get_upload_to(instance, filename):
return 'bulkafbeeldingen/%s/%s' % (instance.bulknummer, filename)
class Overig_Beeld(models.Model):
file = models.FileField(upload_to=get_upload_to)
bestandnaam = models.CharField(max_length=256, null=True)
upload_date = models.DateTimeField(auto_now_add=True)
bulknummer = models.ForeignKey(Bulk, null=True)
tekst = models.CharField(max_length=512)
形式:
class Overig_BeeldForm(forms.ModelForm):
file = forms.FileField()
tekst = forms.CharField(required=False)
class Meta:
model = Overig_Beeld
fields = ('file', 'tekst')
模板:
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<label for="file">Bestand:</label>
<input type="file" name="file"/>
<input type="text" name="tekst"/>
<input type="submit" value="Upload" />
</form>
查看:
if request.method=="POST":
upload = Overig_BeeldForm(request.POST, request.FILES)
if upload.is_valid():
f = request.FILES['file']
Overig_Beeld.objects.create(file=f, bestandnaam=f.name, bulknummer=bulk, tekst=upload.tekst)
return redirect(reverse('bulk', args=(bulk.slug,)))
錯誤:
'Overig_BeeldForm' object has no attribute 'tekst'
感謝安德烈,我不熟悉cleaned_data,我將需要尋找到它作爲你的建議,目前拋出我的錯誤:'異常值:U「鍵,「cleaned_data '沒有在'Overig_BeeldForm'中找到'「' – marckr
@marckr我的bad'cleaned_data'是屬性,不是關鍵。已更新答案 –
非常感謝!完美的作品! – marckr