我无法上传和保存带有文本值的文件作为说明。我不明白为什么:形式和模型显然有相关的领域。当我从视图中删除对文本字段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'
答案 0 :(得分:1)
上传的数据包含在django表单实例的cleaned_data
属性中。所以
text = upload.cleaned_data['tekst']
将解决您的问题