Reputation: 3949
I have a template with two forms like this and two textareas where the uploaded content will be returned:
<form
class="form-inline"
role="form"
action="/controlepunt140"
method="POST"
enctype="multipart/form-data"
id="form_pdf"
>
<div class="form-group">
{% csrf_token %} {{ form_pdf }}
<button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button>
</div>
</form>
<div class="form-outline">
<div class="form-group">
<textarea class="inline-txtarea form-control" cols="70" rows="25">
{{content}}</textarea
> <form
class="form-inline"
role="form"
action="/controlepunt140"
method="POST"
enctype="multipart/form-data"
id="form_excel"
>
<div class="form-group">
{% csrf_token %} {{ form }}
<button type="submit" name="form_excel" class="btn btn-warning">Upload!</button>
</div>
</form>
<textarea class="inline-txtarea form-control" cols="65" rows="25">
{{content_excel}}</textarea
>
and the views.py:
class ReadingFile(View):
def get(self, request):
form = ProfileForm()
return render(request, "main/controle_punt140.html", {
"form": form
})
def post(self, request):
types_of_encoding = ["utf8", "cp1252"]
submitted_form = ProfileForm(request.POST, request.FILES)
content = ''
if submitted_form.is_valid():
uploadfile = UploadFile(image=request.FILES["upload_file"])
name_of_file = str(request.FILES['upload_file'])
uploadfile.save()
for encoding_type in types_of_encoding:
with open(os.path.join(settings.MEDIA_ROOT,
f"{uploadfile.image}"), 'r', encoding=encoding_type) as f:
if uploadfile.image.path.endswith('.pdf'):
pass
else:
content = f.read()
return render(request, "main/controle_punt140.html", {
'form': ProfileForm(),
"content": content
})
return render(request, "main/controle_punt140.html", {
"form": submitted_form,
})
and forms.py:
class ProfileForm(forms.Form):
upload_file = forms.FileField()
and urls.py:
urlpatterns = [
path('', views.starting_page, name='starting_page'),
path('controlepunt140', views.ReadingFile.as_view(), name='controlepunt140')
]
So this works for the first upload function(pdf). The output is returned to the textarea.
But how to have it also work with the second upload function content_excel?
I.E: how to distinguish the two upload functions?
So this part:
return render(request, "main/controle_punt140.html", {
'form': ProfileForm(),
"content": content
})
return render(request, "main/controle_punt140.html", {
"form": submitted_form,
})
Would be double? one for pdf and one for excel
Upvotes: 0
Views: 50
Reputation: 1094
According to the name of the submit buttons:
#FORM PDF
<button type="submit" name="form_pdf" class="btn btn-warning">Upload!</button>
#FORM EXCEL
<button type="submit" name="form_excel" class="btn btn-warning">Upload!</button>
So, in your views.py you can distinguish them on this way:
if request.POST.get('form_pdf'):
....
elif request.POST.get('form_excel'):
....
Upvotes: 2