I wanted to store the content of an uploaded .txt file (with newlines) in a variable, so that I could call my other functions on that variable. But I can not find a way to achieve this. I tried all the methods, but it doesn't work
Here is the simple code example:
Template
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="txt">
<button type="submit" name="encode">Encode</button>
</form>
View
from .algorithms.algo import encoder
def encoder(request):
context = {'encoded':''}
if request.method == 'POST':
text = request.FILES['txt'].read()
encoded = encoder(text)
context['encoded'] = encoded
return render(request, 'template.html', context)
Also, when I tried to output the file, it showed me some strange text instead of the actual content of the file.
Please admins don't close this question, I've surfed all over the internet, but didn't find the answer for my question
Or is there a way to get the value from `textarea`, and store it in a variable with newlines?
Try:
text.decode("utf-8")
or
encoded.decode("utf-8")
before contexting the value
You need to decode the content first because the data you are reading is in bytes. You can do this by changing:
text = request.FILES['txt'].read() to text = request.FILES['txt'].read().decode()
or you can decode it after with:
text = text.decode()
Related
I have a list of tuples in this format: [(a,b,c), (d,e,f),(g,h,i)]. For some reasons, I need to pass it as a hidden field in my form and in my views I need to retrieve it. However, Im not able to do it.
Here is my code snippet:
html template
<form id="form1" action="{% url 'job_recommendations' %}" method="POST">
{% csrf_token %}
<a onclick="document.getElementById('form1').submit();">View more recommendations </a
<input type="hidden" name="recommendations" value="{{ job_recommendations }}"> #it
is the list that I want to pass. It already has correct values
</form>
views.py
def job_recommendations(request):
if request.method == "POST":
recommendations = request.POST['recommendations']
for job, recruiter, percentage in recommendations:
print(percentage)
return render(request, 'recommendations.html')
It's not the best way to do this, but you can use ast module.
Jinja would put [(a,b,c), (d,e,f),(g,h,i)] as string in template. You would get this string in your view, then you can call ast.literal_eval(str) function on this string to convert this string into list.
Please remember that this is very unsecure because it allows user from frontend to execute code on backend.
Good evening,
I'm trying to select a file ("example.csv") via a input inside my template:
main.html
...
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myFile">
<button class="btn btn-success" type="submit">Choose</button>
</form>
...
After selecting and hitting the button I want to achieve the full path plus the name of the file itself as a string!
views.py
...
if request.method == 'POST' and request.FILES['myFile']:
myFile = request.FILES['myFile']
file_path = # getting the full file path
...
For example:
data_name = 'example.csv'
file_path = 'C:\Users\John Doe\Files'
So the string should look something like this: 'C:\Users\John Doe\Files\example.csv'
I tried it with os.path, but this doesn't seem to work or I'm doing something wrong here!?
Thanks for all your help!
It's not possible to get the user's local path of the file, the browser doesn't give such information. Usually the information you get is the Size, Type, Filename.
Check This, This and This
Basically when a POST request is made, I want to redirect to another page.
def sample(request):
if request.method != "POST":
return render(request,"user/sample.html")
else:
return redirect("https://www.djangoproject.com")
This code works fine when it receives a GET request but when I submit
information, instead of redirecting to the page above, it appends the the template name into the url, Something like this :
http://localhost:8000/sample/sample
No matter what I type into the redirect(), even completely random things it still redirects to sample/sample
I've created multiple django-projects and in every one of them I still get this problem.
I've fixed the problem, leaving this here for anyone in the future.
My problem was in the html file
<form action="" method="POST">
{% csrf_token %}
{{form}}
<input type="submit">
the <form action=""> must be an empty string, otherwise it is going to append that to the url.
The problem had nothing to do with the redirect() function.
I created an input form to get the data into web and use the inputs for an AP call.
When I want t refresh the page, there is a popup asking if you want to refresh the input. This is very annoying.
The solution was to use HttpResponseRedirect, which workout nicely, but it's throwing away all the inputs. Then the though would be to use variable in the URL with "URL?rds=2".
How do you get the input variables through the HttpResponseRedirect to the same site?
And also how to get variables from URL to input and from input to the URL?
HTML input definition:
<form action="{% url 'page' %}" method="post">
{% csrf_token %}
<input type="number" value="{{request.GET.rds}}" name='rds'>
<input type="submit" value="Search">
</form>
views.py:
Getting the data from the URL input
if 'rds' in request.GET.keys():
radius = request.GET.get('rds')
else:
request.GET.rds = '3'
radius = '3'
Redirecting input if user pressed. Add more variables with "&" if needed.
if request.method == 'POST':
radius = request.POST.get('rds')
redirect_link = request.path_info + '?rds=' + str(radius)
return HttpResponseRedirect(redirect_link)
This will redirect the radius to the same page and will put rds as a get attribute, which will be fatched by the if method.
Afterwards you can use the data with.
context = {'radius': radius}
return render(request=request, template_name='realestate/page.html', context = context)
I hope this is helpfull. Maybe there is also a way better solution then this.
Situation: An html form (with the method="POST" and enctype="multipart/form-data" attributes set properly) is submitted to the server, which is Django on Google's AppEngine. It contains a file input, which is moved (not cloned) into said form and submitted through an iframe. For small files (~1mb or less) the submitted files are being found in the request.FILES dictionary, and stored in a blob. For files above 1mb, however, the look into request.FILES is returning an error, claiming the key (which is the name of the file input element) is not found in the given dict, and in fact that the request.FILES (and request.POST) dicts are empty.
Question: Is this due to a AppEngine limitation (if so, is there a workaround?) Is this related to Django in some way (do note that the enctype and method are set appropriately)? Is there some other element that is missing?
Additional Information: Please also note that I am a javascript programmer filling in for an absent Python programmer, and know only the basics. Please tailor your answers accordingly.
Relevant Python:
def media_image_upload(request):
if request.method == 'POST':
img = request.FILES['img']
Relevant html:
<form id="hiddenUpForm" style="display:none;" action="http://localhost:8080/media/imageUpload" enctype="multipart/form-data" target="upTarget" method="POST">
<input name="img" id="img" type="file" accept="image/*">
<iframe id="upTarget" name="upTarget" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
I believe that in order to upload files that are larger than 1 MB, you need to use the Blobstore API to create a special URL that is used for the upload; it can't be your regular <1 MB URL.
The controller code that generates the HTML page that contains the upload form would use upload_url = blobstore.create_upload_url('media/imageUploadBig') and would then add upload_url to your template values and render the template.
The template, in turn, would contain a FORM definition something like this:
<form id="hiddenUpForm" style="display:none;" action="{{ upload_url|safe }}" enctype="multipart/form-data" target="upTarget" method="POST">
This means that you either need to have two different forms -- one for files that are less than 1 MB and one for files that are larger -- or you can store all of your images in the Blobstore.
See the Blobstore docs for more information.