簡體   English   中英

無法在 Django 中上傳文件

[英]Can't upload file in Django

創建了 UpdateView,但無法使用 forms 上傳文件來更新 model。 提供下面的代碼。 print(form.cleaned_data) 在回溯中返回文件 None

模型.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

`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,
        }`

視圖.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)`

追溯

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

enctype="multipart/form-data"添加到您的表單中:

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

請注意, request.FILES僅在請求方法為POST時才包含數據,至少實際發布了一個文件字段,並且發布請求的具有屬性enctype="multipart/form-data" 否則, request.FILES將為空。

文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM