I am working on pdf data extraction project.there i am browse pdf file using django-forms filefield and then displaying extracted data on same page.everything works fine but the problem is after submitting browsed file, extracted data appear on same page but browse button get disappear.
forms.py
class browse(forms.Form):
file = forms.FileField()
views.py
def index(request):
if request.method == 'POST':
user = browse(request.POST, request.FILES)
if user.is_valid():
handle_uploaded_file(request.FILES['file'])#store file in upload folder
path = "pdfextractor/static/upload/"+ str(request.FILES['file'])#path of selected file
result = extract_data(path)#extract data from file
context = {'result':result}
return (render(request,'pdfextractor/index.html',context))
else:
user = browse()
return render(request,"pdfextractor/index.html",{'form':user})
index.html
<body>
<form method="POST" class="post-form" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="Submit" name="submit" value="Submit"/>
</form>
{% for key, value in result.items %}
<h1>{{key}} : {{value}}</h1>
{% endfor %}
</body>
output
here you can see browse button disappear.now here i want that browse button so that user can browse new file directly from here
In the POST
part of the request, the form is not being populated through the context
while in the else clause it is being done.
You can create a new form and add it to context:
context = {
'result': result,
'form': browse(),
}
But, do note that in template form is rendered above the results so it will push the result down in the page when visible.
It's because your form is not included in your if
statement so it becomes None
.
def index(request):
result = None
form = None
if request.method == 'POST':
form = browse(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file']) # store file in upload folder
path = "pdfextractor/static/upload/"+ str(request.FILES['file'])#path of selected file
result = extract_data(path) # extract data from file
else:
form = browse()
context = {"form": form, "result": result}
return render(request,'pdfextractor/index.html', context)
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.