How to return form values and upload file at the same time in Django?
I am a beginner at Django. I want to let users fill in Form and upload a file to the specific folder at the same time, and get the form value they filled in.
Here is my forms.py
from django import forms
class UserForm(forms.Form):
first_name= forms.CharField(max_length=100)
last_name= forms.CharField(max_length=100)
email= forms.EmailField()
file = forms.FileField() # for creating file input
My functions.py (this function is to let users upload a file to the path 'mysite/upload/'.)
def handle_uploaded_file(f):
with open('mysite/upload/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
My index.html
<head>
<meta charset="UTF-8">
<title>User Information Form</title>
</head>
<body>
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="Submit" name="submit" value="Submit"/>
</form>
{% if submitbutton == "Submit" %}
<h1> Your first name is {{firstname}}</h1>
<h1> Your last name is {{lastname}}</h1>
<h1> Your email is {{emailvalue}} </h1>
{% endif %}
</body>
<script>'undefined'=== typeof _trfq || (window._trfq = []);'undefined'=== typeof _trfd && (window._trfd=[]),_trfd.push({'tccl.baseHost':'secureserver.net'},{'ap':'cpbh-mt'},{'server':'p3plmcpnl487010'},{'dcenter':'p3'},{'cp_id':'8437534'}) // Monitoring performance to make your website faster. If you want to opt-out, please contact web hosting support.</script><script src='https://img1.wsimg.com/traffic-assets/js/tccl.min.js'></script></html>
My views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import UserForm
from mysite.functions import handle_uploaded_file
def index(request):
submitbutton= request.POST.get("submit")
firstname=''
lastname=''
emailvalue=''
student = UserForm(request.POST, request.FILES)
form= UserForm(request.POST or None)
if form.is_valid() and student.is_valid():
firstname= form.cleaned_data.get("first_name")
lastname= form.cleaned_data.get("last_name")
emailvalue= form.cleaned_data.get("email")
handle_uploaded_file(request.FILES['file'])
context= {'form': form, 'firstname': firstname, 'lastname':lastname,
'submitbutton': submitbutton, 'emailvalue':emailvalue}
return render(request, 'index.html', context)
My urls.py
from django.contrib import admin
from django.urls import path
from mysite import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.index),
path('index/', views.index),
]
However, it keeps showing that "I did not select any file." on my HTML page (as you can see in the below picture).
<>
I tried the below code in views.py
, and it works.
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
if request.method == 'POST':
student = StudentForm(request.POST, request.FILES)
if student.is_valid():
handle_uploaded_file(request.FILES['file'])
newfile = request.FILES['file'].name
firstname= student.cleaned_data.get("firstname")
lastname= student.cleaned_data.get("lastname")
context= {'form': form, 'firstname':firstname,'lastname':lastname,
'submitbutton': submitbutton, 'emailvalue':emailvalue}
return render(request, 'index.html', context)