Django表单无法验证

时间:2018-06-21 03:08:07

标签: django validation amazon-s3

我正在尝试使用Django将文件上传到Amazon S3存储桶。 我创建了一个html表单,并将POST数据传递到基于函数的视图。我环顾四周并尝试了许多尝试,但似乎无法对其进行验证。

(如果相关的话:我已经在设置中配置了S3设置,并且似乎可以很好地处理静态文件)

打印到控制台时出错:

ValueError: The Document could not be created because the data didn't validate.

<ul class="errorlist"><li>upload<ul class="errorlist"><li>This field is required</li></ul></li></ul>

编辑: 似乎只有在模型表单中设置name="upload"时,即使设置输入fields = "__all__",验证也将起作用。这打破了我为表单输入数量可变的要求。

模型

from django.db import models
from django.conf import settings
from django.contrib.auth.models import User

from messaging_platform.storage_backends import PrivateMediaStorage


class Document(models.Model):
    uploaded_at = models.DateTimeField(auto_now_add=True)
    upload = models.FileField()


class PrivateDocument(models.Model):
    uploaded_at = models.DateTimeField(auto_now_add=True)
    upload = models.FileField(storage=PrivateMediaStorage())
    user = models.ForeignKey(User, related_name='documents', on_delete=models.CASCADE)

ModelForm

from django import forms
from apps.core.models.document import Document


class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document
        fields = ('upload',)

查看

def edit(request, message_id=None):
    user_obj = get_login_user_objects(request)

    if request.method == 'POST':
        # tried all of these three variants
        form = DocumentForm(request.FILES['content_url_0'])
        form = DocumentForm(request.FILES)
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()

模板

{% for img_upload in img_upload_list %}
    <input type="file" accept="image/*" class="form-control border-input input-child" placeholder="https://example.com/original.jpg" name="content_url_{{ forloop.counter }}" value="{{ img_upload.payload }}" required>
{% endfor %}

1 个答案:

答案 0 :(得分:2)

因为您表单的字段名为upload django期望发布数据中具有相同的名称。因此,您应该在模板name=upload中重命名字段:

<input type="file" accept="image/*" class="form-control border-input input-child" placeholder="https://example.com/original.jpg" name="upload" value="{{ img_upload.payload }}" required>

此后,您将可以使用以下简单的方法来验证表单:

form = DocumentForm(request.POST, request.FILES)

如果您想同时上传多张图片,则可以使用formset或遵循文档中描述的this method