I'm building a Django app and I would like to have a view/function add a line of html to the inner html of a specific div element with an id every time it is run.
I know how to do this with Javascript but then I would need the view to run that script every time it runs.
Is there a way to do this in the Python document?
The title of your question asks about creating a DOM Element in python. In order to do so, inside your views.py
from django.template import Context, Template
def in_some_view(request):
template = Template('<div class="new-dom-element">Element</div>')
'''
You can create elements above. You can even give it Context Variables
For example: template = Template('<div class="new-dom-element">{{ context_variable }}</div>')
'''
context = Context({'context_variable': your_python_variable})
#By sending the context variable "your_python_variable", you can do anything iteratively.
dom_element = template.render(context)
#Now you can return this dom_element as an HttpResponse to your Javascript.
#Rest of your code.
return HttpResponse(dom_element)
Note: I answered this keeping in mind that you don't want to take a way outside the domain of AJAX requests. If so, then it's really difficult to bring and append some data if an HTML is already displayed on the browser screen. That's exactly why AJAX was created in the first place.
Hope this helps. Thanks.
Related
In my app.py I added a python fuction (to track events) like this:
app = flask.Flask(__name__)
app.jinja_env.globals.update(track_event=track_event)
def track_event(category, label, action):
do="something"
In my HTML code I added it like this:
<a href="somewebsite.web"
class="button button-rounded tright button-large topmargin-sm"
onclick="{{ track_event(category='outbound',action='stackoverflow',
label='somewebsite.web') }}"
>
On this side I offer a listing and therefore add this kind of HTML snipped several times with different URLS (instead of somewebsite.web).
Here is my problem: Instead of being activated "onclick", everytime I load the website all of the onclick events are immediately activated once the browser finished loading.
The functions works as expected, but it shouldnt be called unless someone actually clicks on the . Did anyone have a similar experience?
Is my error in Python or HTML?
In a comment you mentioned that, in the rendered HTML, you had onclick="None". The problem is that your function
def track_event(category, label, action):
do="something"
doesn't return anything. Jinja is going to do what you tell it to do and put the return value of that function in the template. If you return None (which is implicit: if you never explicitly return, you return None by default).
I have an x view that redirects me to some_name.html page.
This view needs to create a class that it is importing from other python file.
This view calls a specific function (algorithm) that has some logic in it.
lets say this func return a dictionary.
I want that view 'x' will redirect me to negotioate.html page with this dynamic return dictionary.
When the user gets the output he should choose from 3 options and basically trigger the algorithm again.
Meaning, I want in each of those trigger to display the user the algo output but without reidrecting me to other page, but refreshing the current one.
Try :
url(r'^(?P<object_id>\d+)/$', edit, name="edit"),
OR
Return :
return redirect('quizzes.views.quizView', quizNumber=quizNumber)
Hi you can redirect from one view to another with data.
Try this code which I am using for my project also.
def notification_view(request,pk):
notification_to_edit=notifications.objects.get(pk=pk)
notification_to_edit.viewed = True
notification_to_edit.save()
return HttpResponseRedirect(reverse('taskdetail',kwargs={'pk':notification_to_edit.task_id.id}))
You need to use AJAX method to avoid page refresh. This view will reload the page, but code should work fine.
I was trying to experiment with the loadhook function in web.py, however I am not quite able to make it work. Here is my code:
import web
render = web.template.render('templates/')
urls = (
'/(.*)', 'index'
)
class index:
def GET(self, name):
return render.base(name)
def test():
print "damn"
render.base("test")
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
app.add_processor(web.loadhook(test))
The base.html template is pretty simple which echoes back the "name" parameter.
What I understood from the documentation was that the loadhook function will be called before every request. But it doesn't seem to work. I have tried going to the homepage, another page etc. Neither do I see a print statement on my CMD, nor does the base template with the name test gets executed.
I tried running the same code with just the add_processor as well, but no luck.
Can anyone help me figure out how to run a function before a request happens on a page?
Also, I am assuming request only encompasses browser level requests. Is there any way to capture more via web.py? (such as call a function on keypress, mouse click etc.)
Any help is much appreciated!
loadhooks are called early in the processing and are used to either set configuration or intercept. For example, I implement a black list similar to the following:
def my_hook():
# If requester's IP is in my blacklist, redirect his browser.
if blacklist.in_blacklist(web.ctx.ip) and web.ctx.path != '/blacklist':
raise web.seeother('/blacklist')
....
app.add_processor(web.loadhook(my_hook))
In your example, your test hook calls render (I'm guessing you're trying to render the test page?) Problem is loadhooks don't return data to the browser, so calling render here doesn't do what you want.
Couple other issues: you need to call app.add_processor(web.loadhook(my_hook)) prior to calling app.run(), because the latter sets your polling loop & never returns.
As for your final question: to capture keypresses, etc. you need your javascript to send something to the server.... Everytime there's a keypress, do an ajax call to the server to log the action.
Python's powerful, but still can't read minds.
I am using webpy framework. I want get current request's url in webpy.
please help me, thanks.
Just try printing web.ctx in your controller method and you will see a bunch of environmental variables.
from pprint import pprint
pprint(web.ctx)
So your url probably should be ctx.home + ctx.path + ctx.query or ctx.home + ctx.fullpath.
UPD: You may also take a look at web.url and web.changequery, find them in api docs: http://webpy.org/docs/0.3/api
Is ctx path what you are after?
Data Found in ctx
Request
path – the path requested by the user, relative to the current
application. If you are using subapplications, any part of the url
matched by the outer application will be trimmed off. E.g. you have a
main app in code.py, and a subapplication called admin.py. In code.py,
you point /admin to admin.app. In admin.py, you point /stories to a
class called stories. Within stories, web.ctx.path will be /stories,
not /admin/stories. E.g. /articles/845
I am a beginner python programmer, and I am working on a selenium project in python 2.7.
I have a generic scraper script, that basically outlines what I want to do with all the websites that I visit. However, because of the nature of the data that I want to grab, I can't run the same code on each site-- each site needs to run it's own individual code.
I have attempted to solve this by importing inside of an if statement, and this is the solution I came up with:
site = False
if source_website == "Website A":
from website_a import *
site = True
elif source_website == "Website B":
from website_b import *
site = True
else:
print "This is not an acceptable website!"
if site == True:
# main code block
driver = driver_setup(chrome)
driver.get(source_website_URL)
stuff_to_save = do_some_stuff(driver)
xml_file(stuff_to_save)
driver.quit()
where the website_a and website_b modules both have functions named do_some_stuff, and they do stuff specific to the website that they're on. Now, this seems to work, for the most part. I also seem to be able to extend functionality to any number of websites, given that I program a module called website_c with the function do_some_stuff, and add that to the conditional import.
So, my question is, is this a good idea? Is there a better way to do something like this?
I have literally never seen anyone wrap import statements inside of if statements like this-- and generally, if no one seems to do it, there's usually a good reason why.
In general, from somewhere import * is not a good idea due to namespace pollution. If you want the website-specific code in separate modules, why not do something like
import importlib
website_modules = {'Website A': 'website_a', 'Website B': 'website_b'}
# ...
website = importlib.import_module(website_modules[source_website])
# use with website.function_name
Explore the page object model pattern (http://code.google.com/p/selenium/wiki/PageObjects). You should model each page as a unique entity, then have some logic that determines what page type you are displaying (either explicitly by having you specify it or implicitly by inspecting the URL and the contents of the page) and then expose the methods to capture the data you need on those objects rather than working directly with the webdriver instance. You should ultimately aim for something like:
for page_identifier in ['page1', 'page2', 'page3']:
page = navigate_to(page_identifier)
extracted_data = page.get_data()
xml_file.write(extracted_data)