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">
Related
I am using python-docx to save a word file and I have set a specific path but since path aren't the same for every user I would like to have a dialogue when the user clicks on download so he can choose exactly in which local repository to save the file.
What I have now:
#app.route('/download_file')
def save_doc():
filename = 'test.docx'
filepath = os.path.join(r'C:\Users\Joe\Desktop', filename)
document.save(filepath)
return 'meh'
Implementing the logic you described requires work on the front-end. Let's simplify the problem by assuming that the user manually types in the download target directory. (In practice, it would make more sense for there to be a pop-up window allowing the user to browse the directory on a file explorer.)
<form action="/download" method="post">
<input type="text" value="" name="dir">
<input type="submit" value="Download">
</form>
Then, in Flask, you might specify the following:
from flask import Flask, request
#app.route('/download', methods=['GET', 'POST'])
def save_doc():
if request.method=='POST':
download_dir = request.form['dir'] # Access user input from backend
filename = 'test.docx'
filepath = os.path.join(download_dir, filename)
document.save(filepath)
return 'Download complete'
else:
pass # Whatever implementation you want for 'GET' method
This is incomplete code that I wrote without knowledge of the structure of your project, and so may not work if it is simply copied and pasted into your source code. The implementation is also quite basic, so consider it a baseline model to help you get started on baking the user interactive dialogue system.
I'd be happy to answer any questions you might have.
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.
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!
Following http://mongoengine.org/docs/v0.4/guide/gridfs.html documentation about mongoengine FileField I did the following:
In my model
files = ListField(FileField())
In my test code
# Create an entry
photo = FileField()
f = open('/home/foo/marmot.jpg', 'r')
photo.put(f, content_type='image/jpeg')
entry.files = [photo,]
Trying to follow the doc, however i get an error:
Traceback (most recent call last):
File "/home/bar/tests.py", line 76, in test_MongoDGACLogook_creation
photo.put(f, content_type='image/jpeg')
AttributeError: 'FileField' object has no attribute 'put'
Am I missing something obvious ?
Thanks
This isn't obvious at all IMO, but if you look at the Mongoengine code you'll see that the put method is defined in the GridFSProxy class, which is accessed via a descriptor in FileField (the __get__ and __set__ methods).
Looking at the code and the examples in the docs, it appears the only way to access or use a FileField is through the descriptor....so, collection.file_field.
Given all this, I don't think it's possible to have a list of file fields using the Mongoengine API as it exists now.
f = mongoengine.fields.GridFSProxy()
to_read = open('/home/.../marmot.jpg', 'r')
f.put(to_read, filename=os.path.basename(to_read.name))
to_read.close()
If you are uploading multiples files and trying to save it a ListField(FileField())
<input type='file' name='myfiles' multiple="">
files = []
for f in request.FILES.getlist('myfiles'):
mf = mongoengine.fields.GridFSProxy()
mf.put(f, filename=f.name)
files.append(mf)
entry.files = files
entry.save()
I had exactly the same problem. As suggested by #KoppeKTop on GitHub in this post, I finally extended my model (Pet) using an EmbeddedDocument like this:
class OneImage(mongoengine.EmbeddedDocument):
element = ImageField()
class Pet(mongoengine.Document):
photos = EmbeddedDocumentListField(OneImage)
# ...more fields... #
I can then add a new image using
i = OneImage()
i.element.put(form.photo.data.stream)
entry.photos.append(i)
entry.save()
This may not always be the best option, but personally I prefer it because I can work with models as usual without having to work with proxies. And I can also save other photo metadata in the future, if I need to.
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