Flask-Admin: Export CSV - flask

I am trying to export a ModelView's data to CSV. Activating can_export = True as recommended in the docs does nothing.
I inspected my Flask-Admin installation, and even though it was the latest version (1.3.0), the source is different, so I downloaded and installed the master.zip available on GitHub.
Now, the Export button appears on my View, but clicking it generates BuildError: ('tableview.export_csv', {}, None)
I tried manually pasting the source's export_csv method into my class (which seems kludgy), but all I get is an empty CSV file.
How can I let the user download a CSV with the table view data?
My code for reference:
class DataTable(Secure):
def __init__(self, modelclass, session, **kwargs):
super(DataTable, self).__init__(modelclass, session, **kwargs)
self.can_export = True
self.column_filters = [c[0] for c in self._list_columns]
# Add view to menu
admin.add_view(DataTable(modelclass, name='TESTE', category=u'TEST'))

Solved:
There were multiple versions of Flask-Admin installed: All of these were 1.3.0, but Flask-Admin's code on GitHub changed without changing the version number. I manually deleted offending folder my environment's site-packages.
Flask-Admin's master.zip on GitHub does not contain the exact code as the website. This is not obvious, and I only found out because I needed a feature that was listed in the Documentation, but did not actually exist on master.zip, only on the Web version.

Related

Automatic file download in Django

I am creating a file download functionality on link click from admin panel in django. I am using FileField for storing the files. For the download purpose I researched and found help on stackoverflow. After using that help, I have the following code for file download (with some minor changes of my own).
def pdf_download(request):
#print("request: ", request.META["PATH_INFO"])
a = request.META["PATH_INFO"]
#print(type(a))
a = a.split("/")
a = a[-1]
#print(a)
#print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
with open(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"\\router_specifications\\"+a ,"rb") as pdf:
#Here router_specifications is the directory on local storage where the uploaded files are being stored.
response = HttpResponse(pdf.read()) #can add ', content_type = "application/pdf" as a specific pdf parameter'
response["Content-Disposition"] = "attachment; filename ="+a
pdf.close()
return response
Now, when I this code runs in my laptop, the file is downloaded automatically. but, when I switch to some other laptop, it asks me where should I save the file i.e. it's not automatically getting downloaded.
What changes should I do so that the file automatically gets downloaded without asking for manual save. Requesting help at the earliest.
You can try adding the following content_type:
content_type='application/force-download'

How to install LaTeX class on Heroku?

I have a Django app hosted on Heroku. In it, I am using a view written in LaTeX to generate a pdf on-the-fly, and have installed the Heroku LaTeX buildpack to get this to work. My LaTeX view is below.
def pdf(request):
context = {}
template = get_template('cv/cv.tex')
rendered_tpl = template.render(context).encode('utf-8')
with tempfile.TemporaryDirectory() as tempdir:
process = Popen(
['pdflatex', '-output-directory', tempdir],
stdin=PIPE,
stdout=PIPE,
)
out, err = process.communicate(rendered_tpl)
with open(os.path.join(tempdir, 'texput.pdf'), 'rb') as f:
pdf = f.read()
r = HttpResponse(content_type='application/pdf')
r.write(pdf)
return r
This works fine when I use one of the existing document classes in cv.tex (eg. \documentclass{article}), but I would like to use a custom one, called res. Ordinarily I believe there are two options for using a custom class.
Place the class file (res.cls, in this case) in the same folder as the .tex file. For me, that would be in the templates folder of my app. I have tried this, but pdflatex cannot find the class file. (Presumably because it is not running in the templates folder, but in a temporary directory? Would there be a way to copy the class file to the temporary directory?)
Place the class file inside another folder with the structure localtexmf/tex/latex/res.cls, and make pdflatex aware of it using the method outlined in the answer to this question. I've tried running the CLI instructions on Heroku using heroku run bash, but it does not recognise initexmf, and I'm not entirely sure how to specify a relevant directory.
How can I tell pdflatex where to find to find the class file?
Just 2 ideas, I don't know if it'll solve your problems.
First, try to put your localtexmf folder in ~/texmf which is the default local folder in Linux systems (I don't know much about Heroku but it's mostly Linux systems, right?).
Second, instead of using initexmf, I usually use texhash, it may be available on your system?
I ended up finding another workaround to achieve my goal, but the most straightforward solution I found would be to change TEXMFHOME at runtime, for example...
TEXMFHOME=/d pdflatex <filename>.tex
...if you had /d/tex/latex/res/res.cls.
Credit goes to cfr on tex.stackexchange.com for the suggestion.

Using Stripe in a CoffeeScript file

I have a CoffeeScript file called subscribers.coffee.erb
$(document).ready ->
stripe = require('stripe')('<%= Rails.configuration.stripe[:publishable_key]%>')
$('.pricing-get-started').prop("disabled", true)
$('.verify-coupon').click ->
# use stripe api to verify that the coupon is valid
return
return
The second line does not seem to be working. I have even tried to copy and past my publishable key but that doesn't work either. I think the following problems are:
require('stripe') isn't found
Rails cannot locate the publishable key from the coffeescript file
Note:
I have a working key. I can sign up for subscriptions and everything from my subscribers/new.html.haml.
I am using gem 'stripe'
Any advice would be greatly appreciated!
You're calling stripe = require('stripe'), but require isn't defined by default in javascript. As long as you have stripe.js included in your application before this script is called the require('stripe') line should be unnecessary.
Once Stripe.js is loaded you can set your publishable key via Stripe.setPublishableKey('pk_test_key_here');. If you're using an environment variable, be sure that Rails.configuration.stripe[:publishable_key] is defined in your environment.
Finally, you should be aware that any embedded ruby in an asset file included in your asset manifest (application.js or application.css) will not be called on each request, but will only be called when you run rake assets:precompile. Thus Rails.configuration.stripe[:publishable_key] may not always evaluate to a value you expect.

Getting file uploads to work with Django & Cloudinary

I am trying to use Cloudinary as a CDN and am having some trouble getting file uploads to work properly. I have followed their blog posts and website, but am running into a consistent and very annoying error.
I have a model associated with both an image (a cover photo) and a media object (a PDF or ebook, like a .mobi or .epub). I have a model form set up to create an object:
class NewMediaObjectForm(forms.ModelForm):
class Meta:
model = MediaObject
fields = ('cover_photo', ...)
cover_photo = CloudinaryJsFileField(options={'tags': 'cover_photo'})
Now, I've read this tutorial from Cloudinary and I know that their form looks like this:
class NewMediaObjectForm(forms.ModelForm):
class Meta:
model = MediaObject
fields = ('cover_photo', ...)
cover_photo = CloudinaryJsFileField(options={'tags': 'cover_photo'})
Here's my problem: if I match their level of indention, the generated HTML shows that the input field is getting all of the right Cloudinary stuff attached to it - but the upload itself doesn't work. The page simply refreshes with an error message stating that no image was selected. Importantly, I can see from the generated HTML that the tags I've specified are coming through.
If I use method #1, with my indention, the file uploads to Cloudinary but none of my tags are applied. It also treats everything as an image, giving me a "invalid image file" error when trying to upload anything other than images (such as the ebook files I mentioned earlier).
I want both - how can I get this upload field to work AND get it to respect the options I'm trying to define?
(I do have cloudinary.config called in the appropriate views; I do have cloudinary_includes and cloudinary_js_config in the appropriate templates; I've imported everything and am calling cl_init_js_callbacks on the form in the view.)
One more addition - I am running this on a local machine using manage.py's runserver rather than deploying, if that has any impact on the configuration.
UPDATE:
I found something I was doing wrong. I've fixed it and made things worse.
The necessary jQuery was not being loaded. Now I am loading it, but the upload button simply doesn't function. I press the button, I select the file, the select dialog disappears, and it shows that no file has been selected. However, I can see that the tags are being passed to the generated HTML, so it's a step in the right direction. Any ideas?
Please forgive me. This was a PEBCAK issue; I will leave this visible for anyone else who may make the same mistakes I've made in the future.
Make sure the proper jQuery scripts are being loaded - open the Chrome developer console, Firebug, whatever and double check. Then, make sure they're being loaded after the DOM so that there are elements for the script to attach to.
Cloudinary will expect html/cloudinary_cors.htmlto be accessible in your static directory.
Either I have broken something, or the default behavior for this particular type of ModelField is to simply IMMEDIATELY upload the selected file and continue displaying "No File Chosen." I thought that nothing was happening and was very surprised when I saw 50+ images successfully uploaded.

django-cms editors and HTML data attribute cleaned up

Using django-cms 2.4 I need to create pages that contain bootstrap code, but the html5lib used cleans data-* attributes. No matter if you specify valid_element in TINYMCE_DEFAULT_CONFIG. (I still looking for a similar option for Wymeditor), because this is done in #plugins/text/models (clean_html function: https://github.com/divio/django-cms/issues/1529 )
Github issue:
https://github.com/divio/django-cms/issues/1529
What could it be a possible workaround?
How can I extend the text plugin in the admin part?
Thanks!
i belive the removing of the fields is done by html5lib that the cms uses as python package, you'll need to open html5lib folder and open sanitizer.py, in line 184 where the code is:
if name in self.allowed_attributes])
change to:
if name in self.allowed_attributes or re.match( r'data-.*',name)])
this will allow all data-(whatever) attributes
for WYMeditor the data-(whatever) attribute is already allowed