Reputation: 55
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}`
Upvotes: 0
Views: 759
Reputation: 871
Add enctype="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.
Upvotes: 1