简体   繁体   中英

Can't upload file in Django

Created UpdateView and can't update the model with the file upload using forms. Provided the code below. print(form.cleaned_data) returns file None in the traceback

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

views.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:

<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" . Otherwise, request.FILES will be empty.

Document .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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