So I'm trying to make a form in Django with a FileField.
My forms.py looks like this:
from django import forms
class WordcloudForm(forms.Form):
matrix = forms.FileField(required=True)
min = forms.IntegerField(required=False)
max = forms.IntegerField(required=False)
# mask = forms.FileField(required=False)
I want the FileField to be a required field.
views.py:
def form(request):
if request.method == 'POST':
form = WordcloudForm(request.POST)
print(form.is_valid)
if form.is_valid():
if 'matrix' in request.FILES:
uploaded_matrix = request.FILES['matrix']
print(uploaded_matrix.name, uploaded_matrix.size)
min = form.cleaned_data['min']
max = form.cleaned_data['max']
print('min',min,'max',max)
print(form.errors)
When forms.FileField(required = True)
in forms.py, form.is_valid() returns false:
When forms.FileField(required=False)
in forms.py, form.is_valid() returns true:
When I submit the form with forms.FileField(required = True)
my print(form.errors)
states: "This field is required" even though I do add a file.
I tried different file formats to make sure the problem didn't just occur with the image I was using for testing.
What am I missing?
As mentioned in the documentation you need to pass request.FILES
along with request.POST
when initiating form instance:
if request.method == 'POST':
form = WordCloudForm(request.POST, request.FILES)
if form.is_valid():
# rest of the code
Also please rename your view method from form
to anything meaningful, because you have a variable named form
inside the method. Same with naming of variables min
and max
, they conflict with python's min
and max
functions. Your IDE is already marking them.
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.