Reputation: 1368
I fail to upload a file and get "This field is required." Up until now it's the same as the issue reported here. However, I am using enctype="multipart/form-data"
like suggested in that issue.
The model:
class ContentSheet(models.Model):
content_sheet_name = models.CharField(max_length=500)
content_sheet_file = models.FileField()
The form:
class ContentSheetForm(forms.ModelForm):
content_sheet_name = forms.CharField(max_length=50)
content_sheet_name.widget.attrs.update({'autofocus': 'autofocus', 'placeholder': 'Content Sheet Name'})
content_sheet_file = forms.FileField()
class Meta:
model = ContentSheet
exclude = tuple()
The view:
def add_user_sentence(request):
statistics_context = get_statistics()
if request.method == 'POST':
form = ContentSheetForm(request.POST, request.FILES)
if form.is_valid():
# Save the new sentence to the database.
form.save(commit=True)
print "form.content_sheet_file", form.content_sheet_file
...
else:
print form.errors
else:
# If the request was not a POST, display the form to enter details.
form = ContentSheetForm()
# Bad form (or form details), no form supplied...
# Render the form with error messages (if any).
context = {'user_sentence_form': form}
return render(request, 'lf_classifier/insert_text.html', context)
The HTML:
<form id="user_sentence_form" method="post" enctype="multipart/form-data" action="/lf_classifier/send_text/">
{% csrf_token %}
{% for field in user_sentence_form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" data-icon="action" data-iconpos="right" name="submit" data-inline="true" value="upload" />
</form>
Upvotes: 0
Views: 655
Reputation: 1368
Adding data-ajax="false"
resolved my issue. The fixed HTML:
<form id="user_sentence_form" method="post" enctype="multipart/form-data" data-ajax="false" action="/lf_classifier/send_text/">
{% csrf_token %}
{% for field in user_sentence_form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<input type="submit" data-icon="action" data-iconpos="right" name="submit" data-inline="true" value="upload" />
</form>
Upvotes: 1
Reputation: 599570
You haven't passed the file data to the form.
form = ContentSheetForm(request.POST, request.FILES)
Upvotes: 2