I'm trying to create a Django form with a filefield to upload a pdf based on a model.
#models.py
class ProductionRequest(models.Model):
...
contract_file = models.FileField('Contract file (PDF)', upload_to='contracts/')
...
I can upload the file and save it in my object, but when I try to show the file in my template with this code
{{ prod_req.contract_file }}
it only show me the path to the file
"contracts/file_uploaded.pdf". How can I make a link to download (or open in a new tab ) the file ?
Plus : when I try to open the file from Django admin, with this link
Contract file (PDF) : Currently: contracts/file_uploaded.pdf
I don't show me the file, i got this :
Page not found (404) Request URL: http://127.0.0.1:8000/admin/appname/productionrequest/1/change/contracts/file_uploaded.pdf/change/
How can I access to my file ?
It works just like a Python file. So, the way you have just refers to a file object.
To get the text, you need to use f.read(). So, in your template, instead of
{{ prod_req.contract_file }}
use
{{ prod_req.contract_file.read }}
BUT, note that calling read moves the cursor to the end of the file. The first time you call read on a file, it returns all the text. The second time, it returns nothing. This is only a problem if you need the text twice, but in that case, store the text directly on the context object.
Let me know if anything was unclear.
Related
I am creating a flask web application which asks users to complete a quiz through a form and collect data from each session. I use a main.py file, 1 html file with the quiz, and then another one which is supposed to display dynamic results. When the submit button is clicked, it automatically directs users to the second html page with their results. It is my intention to display results based upon what options the user clicks. I attempted to accomplish this by:
Collecting data:
session["symptom1"] = form.symptom1.data
Writing this into a file
user_data.write(form.symptom1.data)
Reading file contents into a variable (3 characters into each variable)
data1 = user_data.read(3)
Assigning a Boolean value to a python variable based upon the data using a conditional:
if data1 == "op3" or data1 == "op4":
global adhd1
adhd1 = True
Rendering this to an html file:
return render_template("takethequiz.html", form = form,adhd1=adhd1,adhd2=adhd2,adhd3=adhd3,adhd4=adhd4)
Creating a conditional in a second html file (treatmentplan.html)=
{% if adhd1 == True %}
Use productivity apps to increase your focus
{% else %}
Great job! You are skilled at staying on task!
{% endif %}
However this does not do anything. Meaning, no matter what I click, the treatment plan is always set to adhd1 = False. How do I combat this?
Code Screenshots on Google Doc: https://docs.google.com/document/d/1uF1Q-zfKNx-d5jzbaIK_BKGbLRm0tCGgaz92-V2hDjE/edit?usp=sharing
Thank you!
I am developing an application in django 2.1 in which I must upload an undetermined number of audios through a modal and then pass the information to the view from which the modal is launched.
However, these audios should not be stored in the database until the main view form is filled out. Then I thought about these solutions:
First I thought about saving it as a session attribute but the contents of a FileField is not JSON serializable which did not work.
Second I thought about the LocalStorage property but if the files exceed the size I will have problems.
Third I thought about getting the file path and then create the audio but as I was reading is a bad practice and can only be obtained if the file is created on the disk, that is, if it is in TemporaryUploadedFile but my files should weigh less than one 1MB
For which I have the option that all files that are loaded with a size smaller than 2.5MB are stored in InMemoryUploadedFile but I do not know how to obtain them. Does anyone know how this is done? or how else can I save a list of temporary audios?
InMemoryUploadedFile is a wrapper around a file object. You can access the file object using the file attribute.
file_in_memory # <InMemoryUploadedFile: xxx (xxx/xxx)>
file_object = file_in_memory.file
ClientSide :
var file = document.getElementById('file');
const formData = new FormData();
formData.append('file', file[0]);
fetch('api/upload_file/',{
method:'POST',
body:formData
}).then(res => console.log(res);
.catch(error => console.log(error);
On Server Side:
InMemoryUploadedFile can be accessed as:
file = request.FILES.get('file')
I am a new user of Jinja2.I am trying to use Jinja2 template engine with python sphinx. I want to add some loops and variables from jinja to create a html file . My .rst file uses a sphinx template and I am just writing the below line in the file :
{{ a_variable }}
Where do I need to specify the value of this variable (ex. a_variable="hello world") so that "hello world" is displayed in the html file as text.
You specific the variable in your render command.
template = jinja2.Environment(loader=jinja2.FileSystemLoader(["./templates/WebPages"])).get_template("WebPage.html")
return template.render(SomeVariable='something')
Hope this helps!
Currently, I'm using request.params["filename"] to access uploaded files.
In Pylons, what is the syntax to access a file if you don't know the filename, something like request.files[0]?
Based on what this: http://pylonshq.com/docs/en/1.0/forms/#file-uploads page says, you could search through the params or request.POST looking for values of the type cgi.FieldStorage
It's not the file name that's used as a key in request.params, it's the field name that was used in the HTML: <input type="file" name="fieldname">
I tried to use the jquery plugin "uploadify" to upload multiple files to My App in Google App-Engine, and then save them with blobstore, but it failed. I traced the code into get_uploads, it seems field.type_options is empty, and of course does not have 'blob-key'. Where does the key 'blob-key' come from?
the code like this:
def upload(request):
for blob in blogstorehelper.get_uploads(request, 'Filedata'):
file = File()
file.blobref = blob
file.save()
return ……
but, blogstorehelper.get_uploads(request, 'Filedata') is always empty. In fact, the request has contained the uploaded file(I print the request). I debugged into the blogstorehelper.get_uploads, and found that field.type_options is empty. who can tell me why? thank you! here is the source about get_uploads: http://appengine-cookbook.appspot.com/recipe/blobstore-get_uploads-helper-function-for-django-request/?id=ahJhcHBlbmdpbmUtY29va2Jvb2tyjwELEgtSZWNpcGVJbmRleCI4YWhKaGNIQmxibWRwYm1VdFkyOXZhMkp2YjJ0eUZBc1NDRU5oZEdWbmIzSjVJZ1pFYW1GdVoyOE0MCxIGUmVjaXBlIjphaEpoY0hCbGJtZHBibVV0WTI5dmEySnZiMnR5RkFzU0NFTmhkR1ZuYjNKNUlnWkVhbUZ1WjI4TTIxDA