【问题标题】:upload a specific file form Django/Python上传特定文件表单 Django/Python
【发布时间】:2017-05-19 12:36:18
【问题描述】:

我的 django 项目中只有一个上传文件表单(我使用的是 1.10)。实际上一切都很好,但是由于人们会将 csv 文件上传到服务器,我需要将我的逻辑限制为仅请求具有特定名称和格式的文件。

这是我的代码:

views.py

def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('action'))
    else:
        messages.add_message(request, messages.ERROR,
                             'Something went wrong with files! Please contact the system administrator')
        return render(request, 'upaction-report.html')

    # Load documents for the list page

    # Render list page with the documents and the form
    return render(request, 'upaction-report.html', {'form': form})

forms.py

class DocumentForm(forms.Form):
    docfile = forms.FileField(
        label='File format should be under the following format:',
        help_text='- .csv format and under the name "Action_Report"',
    )

模板 html

<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <p>{{ form.non_field_errors }}</p>

    <p>{{ form.docfile.label_tag }}</p>
    <p> {{ form.docfile.help_text }}</p>


    <p>

        {{ form.docfile }}
    </p>

    <p><input type="submit" value="Upload File"/></p>
</form>

猜猜如何应用该限制?如果文件不正确,只需弹出一条消息,告诉重试,直到它具有正确的格式和名称。感谢您的宝贵时间,如果您需要更多详细信息,请告诉我。

【问题讨论】:

    标签: python html django if-statement file-upload


    【解决方案1】:

    您可以像这样在 DocumentForm clean 方法中验证文件名:

    class DocumentForm(forms.Form):
        docfile = forms.FileField(
            label='File format should be under the following format:',
            help_text='- .csv format and under the name "Action_Report"',
        )
    
        def clean(self):
            docfile = self.cleaned_data.get('docfile')
            if not docfile:
                raise forms.ValidationError('file is required')  
            if not docfile.name.startswith('filename'):
                raise forms.ValidationError('incorrect file name')
            if not docfile.name.endswith('fileformat'):
                raise forms.ValidationError('incorrect file format')
            return super(DocumentForm, self).clean()
    

    【讨论】:

    • 您好 neverwalkaloner,感谢您抽出宝贵时间。我到底应该设置这个吗?进入我的views.py?
    • @Deluq 不,您应该在 DocumentForm 类中尝试。我更新了我的答案。
    • 哦,好的,知道了。我收到此错误 AttributeError:“NoneType”对象没有属性“名称”。我应该在某处设置文件名和文件格式吗?
    • @Deluq 你选择了任何文件吗?我想你看到这个错误是因为没有选择文件。您还需要验证 docfile 是否为 None。查看更新的答案。
    • @Deluq 是的,没错。只需插入您的文件名和 csv 作为格式。
    猜你喜欢
    • 2018-10-23
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 2013-10-04
    • 2018-01-25
    • 2015-10-12
    相关资源
    最近更新 更多