简体   繁体   English

无法在 Django 中上传文件

[英]Can't upload file in Django

Created UpdateView and can't update the model with the file upload using forms.创建了 UpdateView,但无法使用 forms 上传文件来更新 model。 Provided the code below.提供下面的代码。 print(form.cleaned_data) returns file None in the traceback print(form.cleaned_data) 在回溯中返回文件 None

models.py模型.py

`from django.db import models

# Create your models here.
class DashModel(models.Model):
    name = models.CharField(max_length=220)
    file = models.FileField(null=True, blank=True)`

forms.py forms.py

`from django import forms 
from .models import *

class AddModel(forms.ModelForm):

    class Meta:
        model = DashModel
        fields = ('name','file')

        widgets = {
            'name' : forms.TextInput(attrs={'class':'form-control'}),
            'file' : forms.FileInput,
        }`

views.py视图.py

`class DashModelUpdateView(UpdateView):
    template_name = 'dashboard/update_model.html'
    form_class = AddModel
    success_url = '/dashboard/search-models/'
    queryset = DashModel.objects.all()

    def form_valid(self,form):
        print(form.cleaned_data)
        form.save()
        return super().form_valid(form)`

Traceback追溯

`[14/Apr/2021 01:00:00] "GET /dashboard/1/update/ HTTP/1.1" 200 16091
{'name': 'Some Name', 'file': None}`

Addenctype="multipart/form-data" to your form:enctype="multipart/form-data"添加到您的表单中:

<form method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Upload</button>
</form>

Note that request.FILES will only contain data if the request method was POST , at least one file field was actually posted, and the that posted the request has the attribute enctype="multipart/form-data" .请注意, request.FILES仅在请求方法为POST时才包含数据,至少实际发布了一个文件字段,并且发布请求的具有属性enctype="multipart/form-data" Otherwise, request.FILES will be empty.否则, request.FILES将为空。

Document . 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM