上传带文字说明的文件

时间:2016-03-25 17:59:51

标签: django upload

我无法上传和保存带有文本值的文件作为说明。我不明白为什么:形式和模型显然有相关的领域。当我从视图中删除对文本字段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'

1 个答案:

答案 0 :(得分:1)

上传的数据包含在django表单实例的cleaned_data属性中。所以

text = upload.cleaned_data['tekst']

将解决您的问题