I have written a view which takes input either from a form where you can post your data directly or you can upload a ".csv" file like this given below:
views.py
def Some_view(request):
if request.method == 'POST':
form = My_form(request.POST)
else:
request.method == 'POST' and request.FILES['myfile']
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'myapp/des.html')
return render(request, 'myapp/des.html', {'form': form})
html template: des.html is like this:
{% extends 'protocol/base.html' %}
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
{% block content %}
<body>
<div class="container">
<div style="width:30%">
<form action="/result_view/" method="post">
{%csrf_token%}
{% for error in form.non_field_errors %}
<div class="form-group has-errors text-danger small">
{{error}}
</div>
{% endfor %}
{% for field in form %}
<div class="form-group has-errors text-danger small">
{{field.errors}}
</div>
<div class="form-group has-errors text-danger small">
</div>
{% endfor %}
<div class="form-group">
{{form.AA}}
</div>
<div class="form-group">
<button class="btn btn-primary" style="width:100%; margin-bottom: 30px ">Submit</button>
</div>
<h2> or <h2>
<style type="text/css">
.button {
background-color: #ff9800; /* Green */
border: none;
color: black;
padding: 10px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-top: 10px;
margin-bottom: 30px;
}
</style>
<form method="post" enctype="multipart/form-data">
<div class="heading">
</h4>
</div>
{% csrf_token %}
<input class="input" type="file" name="myfile">
<button class="button" type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p class="text" >File uploaded successfully. </p>
{% endif %}
</div>
</form>
</div>
</body>
</html>
{% endblock %}
forms.py
from django import forms
class My_form(forms.Form):
AA = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Ex.: ARNDCEQGHILKMFPSTWYV'}))
class Meta:
fields = ['AA']
The form is working fine but in my case upload method is not working, when I use to upload file method alone if works fine but with form method, it is not working please help me out in this regards thanks.
i think you need to change if condition sequence:
if request.method == 'POST' and request.FILES.get('myfile'):
# You code here
elif request.method == 'POST':
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.