sart function from template - python

I know that functions can't (shouldn't) be called directly from the template in Django.
But I can't find out how to properly call a simple function. Here is what I would like to do:
On my template I would like to have a hyperlink to paste all relevant information from the template to the clipboard using pyperclip. We frequently have to copy addresses from the database to paste into a word document or an email.
So, copy the data to a String variable and pass that variable to pyperclip.copy() using a hyperlink.
Seems easy enough but I can't find it out.

If you want to include Python code, use a custom template tag in Django.
It sounds like you want something a bit more complex, though. You won't be able to call pyperclip code on the client side -- there's just no Python execution environment in place.
Instead, look into using Javascript or Flash to copy data to the clipboard.

Related

How to dinamically inject HTML code in Django

In a project of mine I need to create an online encyclopedia. In order to do so, I need to create a page for each entry file, which are all written in Markdown, so I have to covert it to HTML before sending them to the website. I didn't want to use external libraries for this so I wrote my own python code that receives a Markdown file and returns a list with all the lines already formatted in HTML. The problem now is that I don't know how to inject this code to the template I have in Django, when I pass the list to it they are just printed like normal text. I know I could make my function write to an .html file but I don't think it's a great solution thinking about scalability.
Is there a way to dynamically inject HTML in Django? Is there a "better" approach to my problem?
You could use the safe filter in your template! So it would look like that.
Assuming you have your html in a string variable called my_html then in your template just write
{{ my_html | safe }}
And don’t forget to import it!

Zope PostgreSQL variable with HTML and DTML

I have a postgresql db table called blog_post and in that table a column called post_main. That column stores the entire blog post article, including various HTML and DTML tags.
For reference (and yes, I know it's old), this is Zope 2.13 with PostgreSQL 8.1.19
For example:
<p>This is paragraph 1</p>
<dtml-var "blog.sitefiles.post.postimg1(_.None, _)">
<p>This is paragraph 2</p>
The dtml-var tag is telling Zope to insert the contents of the dtml-document postimg1 between the two paragraphs.
OK, no problem. I am storing this data without issue in the postgres db table, exactly as it was entered, and I am running a ZSQL Method via a <dtml-in zsqlmethod> tag that surrounds the entire dtml-document, in order to be able to call to the variables I need in the page.
Normally, and without either HTML code OR especially without DTML tags, it's no issue to insert the data into the web page. You do this via &dtml-varname; if you have no html tags and just want a plain text output, OR you do <dtml-var varname> if you want the data to be rendered and shown as proper html.
Here's the problem
Zope is just posting the <dtml-var "blog.sitefiles.post.postimg1(_.None, _)"> line to the html page instead of processing it like when I type it into the dtml-doc directly.
What I need:
I need the code stored in the post_main column (referenced above as varname) to be processed as if I typed it directly into the dtml-document, so that the <dtml-var> tags work the way they are supposed to work.
So, you have a variable that contains a DTML Document, and you want to execute that document and insert the results?
To be honest, I'm not sure that's possible in DTML alone, as it generally users don't want to execute code contained in strings. This is the same danger as exposing eval() or exec() of user supplied strings, as if someone can control the string they have arbitrary code execution on the Zope instance. It's the equivalent of storing PHP code in your database and executing that.
Frankly, I'm surprised you're using DTML on Zope 2.13 at all, rather than PageTemplates, but I assume you've got a good reason for it.
If you want to interpret the value of a DTML variable rather than just insert it, you'll need to explicitly do the interpreting, using something like:
from DocumentTemplate.DT_HTML import HTML
return HTML(trusted_dtml_string)
The problem with this is that you can't do it in a Script (Python) through the web, because of the security concerns. If you do this as an external method or filesystem code it's very likely that you'll allow arbitrary code execution on your server.
I'm afraid my only recommendation is to avoid doing this, it's very difficult to get it right and errors can be catastrophic. I'd strongly suggest you do not store DTML tags as part of your blog articles.
As an alternative, if you have a fixed number of delegations to DTML methods, I recommend writing a Python script, such as:
## Script (Python) "parse_variables"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=post, _
##title=
##
post = post.replace("##POST_IMAGE##", context.postimg(None, _))
return post
And then calling that with your variable that contains the user-supplied data, like <dtml-var expr="parse_variables(data, _)">

Print an object's URL in Django

OK, I think this is actually simpler than I'm making it, but I can't figure out what to search for in the django documentation.
Here's what I need to do. I'm about to run a script (using the writing custom django-management commands guide) which will add a whole bunch of records to my database. A mass import of all the student data. After I create these 130 new records, I need to create a QR code for each of them. I've found several QR code generator sites, but that's slow as hell and the school won't pay for me to sign up for the ones that come with mass QR code generation. No problem, this is Python. Batteries included!
I have the qrcode module installed, but what I don't understand is how I can get the URL after it creates the object. I know which view I want (the relative url is /awards/student/<student_id>/). I know that in the HTML template language, that {% url 'StudentHome' student.id %} gets me that url. Can I access that from the command line and pass it to qrcode, which would then generate and save the qrcodes as png files?
Use reverse method to reverse a URL.
reverse("url_name", args=(args1))
As for your case
reverse("StudentHome", args=(student.id))
For getting absolute Uri you can use this method.
abs_uri = request.build_absolute_uri(reverse("StudentHome", args=(student.id)))
Refs: docs

How can I modify a sublime text 3 document via the in-app python console?

I want to apply some function to the text of a document.
Like for example run a regexp replacement and then convert the resulting text to lowercase (or some more complicated example that cannot be easily done with the provided tools).
I know how to do this using python, so I could just run a simple script from a python interpreter to load, modify, and save the data back.
This can however be quite annoying, and given the existence of a python API for sublime text there should be a way to directly run a script to modify the open document.
I would also prefer to avoid macros because those would require me to save a .sublime-macro file, but alternative solutions of this sort are equally welcome.
How can I achieve this?
In the sublime console, the symbol view represents the currently focused view (file) while window represents the current window.
So you can use the plugin API method sublime.View.substr() to collect the contents of the currently selected view as a string for further manipulation:
content = view.substr(sublime.Region(0, view.size()))
Or if you wanted, you could select some text first and then grab the contents of the selection. This example grabs only the content of the first selection; modify as needed if you wanted to grab the contents of multiple selections at once.
content = view.substr(view.sel()[0])
From here you can do whatever you want to content. Your issue is in putting the contents back into the buffer when you're done.
All edit operations need to be tracked to allow Sublime the ability to undo the change. For this reason the underlying API requires all calls that would modify the buffer (inserting, appending, or replacing text, etc) to provide an edit object. However these objects are strictly controlled; only Sublime can create one on your behalf.
So the only way to modify the buffer is to either implement your own TextCommand that does it for you, or utilize an existing command via the sublime.View.run_command() method.
content = view.substr(sublime.Region(0, view.size()))
content = content.replace("Hello", "Bonjour")
content = content.replace("Goodbye", "Au Revoir")
view.run_command("select_all")
view.run_command("insert", {"characters": content})
Here I've pulled the text out of the buffer, done some replacements, and then put the entire modified string back into the buffer by first selecting everything and then inserting the new content back.
Note that if you were doing this from a TextCommand, you would need to use self.view everywhere and not just view.
You can launch your script from the Python API, and use and get the contents of the entire file with:
contents = self.view.substr(sublime.Region(0, self.view.size()))

How do I find out what I can do with the Pelican signals? I'm trying to write a plugin

The signals are sort-of described here but, then what?
For example, one of the signals is desribed:
invoked before writing each article, the article is passed as content
How do I change that content? How do I access it? What functions are available?
I've been looking at examples in the pelican plugins repo on github, but I'm still confused. (How did those people even learn how to write those plugins?)
I hardly know where to start.
You have to look at the source code of pelican. I think there is no better way.
For example, search for the signal you are interested in, e.g. article_generator_write_article: https://github.com/getpelican/pelican/search?utf8=%E2%9C%93&q=article_generator_write_article
Then, look into the search result, e.g. generators.py and click on the line number containing your signal. Of course, you could also create a clone and do all this locally. This depends on your way of working.
Surrounding code:
def generate_articles(self, write):
"""Generate the articles."""
for article in chain(self.translations, self.articles):
signals.article_generator_write_article.send(self, content=article)
write(article.save_as, self.get_template(article.template),
self.context, article=article, category=article.category,
override_output=hasattr(article, 'override_save_as'), blog=True)
As you can see, the signal call provides you with an article object. You can now 1) look in the source code to find the respective python class of this object to find out about its inner workings, methods and attributes or 2) go the hacky path and simply print the object's members print(article.__dict__).
I suppose, without having looked in the code, that article has an attribute content which contains the HTML code generated from your source file. This is where your desired change comes in.
Note that if you want to change the source code before processing this is not that easy. I just wrote a little plugin which is capable of doing this.
There you can also see the signal API in action. You simply have to connect a handler function to the desired signal.
I hope this helps :)

Categories

Resources