Python Templating and Ajax - python

I was not able to come up with a better title for this post, so if anybody does not find it appropriate , please go ahead and edit it.
I am using flask as my python framework, and normally I render templates doing somnething like the below:-
#app.route('/home')
def userhome():
data=go get user details from the database
return render_template("home.html",userdata=data)
Now I have a template name home.html in which I iterate over the values of "userdata" like userdata.name, userdata.age etc and these values take their appropriate spaces in the template.
However I am working on an application in which navigation is via ajax and no fall back if javascript is not available(basically the app does not work for ppl without javascript).
The navigation menu has say few tabs on the left ,(home,youroffers,yourlastreads). The right column is supposed to dynamically change based on what the user clicks.
I am unable to understand how I handle templating here. Based on what the user clicks I can send him the required data from the db via a json through an xhrGET or xhrPOST.Does the entire templating have to be handled at the server end and then transfer the entire template via an ajax call. I actually dont like that idea much. Would be great if someone could point me in the right direction here.
Now in the page that is loaded via ajax , there are some scripts which are present. Will these scripts work, if loaded via ajax.

You have two options: template on the server, or template in the browser.
To template in the server, you create an endpoint much like you already have, except the template only creates a portion of the page. Then you hit the URL with an Ajax call, and insert the returned HTML somewhere into your page.
To template in the browser, your endpoint creates a JSON response. Then a Javascript templating library can take that JSON, create HTML from it, and insert it into the page. There are lots of jQuery templating solutions, for example.

I would choose server side templating, because unless you find a JS library that handles the same templating language your code isn't going go be DRY.
In the home.html template, I'd do something like
<%extends base.html%>
<%include _user_details.html%>
... <% footer and other stuff%>
And keep the actual markup in _user_details.html. This way, for an AJAX request you just render the _user_details.html partial only.

Related

Auto refresh HTML database data in Django - Ajax?

I have a Django server which is locally hosted and displays sensor data from a MySQL database. This data is displayed on the instruments.html page through variables such as {{qs.value}} which comes from the views.py, models.py and URLs.py. The views.py page is as follows:
from django.http import HttpResponse
from django.shortcuts import redirect, render
from .models import Sensorresult
def db(request):
qs = Sensorresult.objects.using('Vision').get(sensorresult='1')
return render(request, 'authenticate/instruments.html',{'qs':qs})
The problem I have is that I want the database information to update on the html every second, whereas currently it only updates when the page is refreshed. I know I could place a line of javascript at the top of the page and have the entire webpage constantly update, but I only want the database values to update. Does anyone have any suggestions as to how to do this?
From googling have come across Ajax, however this is something I have no experience in and I am unsure how my code would be edited to accommodate this?
Many thanks
You may want to consider using htmx.
Very simple library which takes away the JavaScript complexity to update parts of a web page rather than a full page reload and allows you to do most of the work in html.
Their docs specifically make reference to polling to update a certain part of the page which seems to be exactly what you’re trying to achieve.
Essentially all you’d need to do is create a view that returns a template partial, then use htmx polling to hit that url and replace a div with the partial the view returns.
Instead of directly using fetched data in HTML, you can try fetching it in javascript.
And if you have ever created the clock with javascript, it does not reload the entire page but still updates the time. You can use the same way to update that fetched data in HTML.

Can I Use One view In a Django Project?

I´m new to web dev,
and I was wondering if it´s possible to make a website, that just need to present information of a company (HTML), in just one view.
Like rendering the entire bootstrap in one view.
Yes, you can serve your HTML code through a TemplateView.
So if your entire single page application sits in home.html you could definitely do this. But there is no point in using Django for only that purpose. You would rather want to serve your static HTML page from a classic web server like nginx or apache.
I don't know why would you want to do that.
You can use different html files which will be served as your website templates. You can also extend the files using a simple base.html file. This will help you if you want to open other links when people click on different links on the website.
See this example: https://github.com/singh1114/Djangosite/tree/master/duggal/webportal/templates/webportal.
For using this you have to know more about views and urls.
For making scrollable things, you need to know the concept of ids in HTML.
For example
http://yoursite.com/#your_name will try to find id your_name in the HTML. This way you can create scrollable things.

How do Bottle and HTML communicate back and forth?

So I am attempting to use bottle.py and twitter bootstrap together to make a small website. I need to be able to insert a reasonable amount of data at various points in the HTML using Python but I am not really sure I understand how the HTML and python are communicating.
Here is an example of twitter and bottle working together.
He mentions linking a couple of .js files in the html and I can see where he does that but I am not really sure how that affects how the python interacts with the html. Is there a callback from the Javascript that the python catches using request.GET.get().strip():?
Also one of the last lines is:
return template('templates/gpio.tpl', colour1=colour1, colour2=colour2, colour3=colour3)
I am not sure how the templates/gpio.tpl is connected to the html he mentions below. I understand that the colour# variables are referenced in the html (I assume this happens with the {{}} syntax) but I am not sure how the html gets called at all.
From what I understand (which so far isnt a whole lot) this is how it goes:
User enters "server:port/gpio" into a webbrowser
The python decorator gets called by bottle and the function is run returning the template at the bottom.
This is where I get confused.
A) How does the python script know to call the html?
B) How does the gpio.tpl template code get sent to the html?
C) Is it safe to assume that the python arguements sent to the template function can be referenced using the {{}} syntax or is there more to it?
D) How does the html call back to the python to update the buttons he shows at the bottom?
D.1) does the JS linked at the top have something to do with this?
Lastly: If anyone has a another/better example of linking bootstrap and bottle I would be very happy to see it.
This is quite a loaded post. Thank you for your patience. :D
You'd really need to first learn how the HTTP protocol works... But let's try to quickly answer your main question:
how the HTML and python are communicating
Quite simply: they don't. What happens is:
your client (usually your browser) send an HTTP request to your site
the front web server (Apache, Nginx, whatever) sends this request to the bottle.py application
the bottle.py app dispatch the request to the right controller function matching the url's path portion and request's method against the defined routes)
the controller function does what it has to do and returns an HTTP response to the front web server
the front web server send this response to your client
Usually - but not necessarily - the HTTP response contains HTML content, generated by the controller using a template. IOW : bottle.py uses the template to generate html that is sent back to the client.
Once the response is sent, there's no more "communication" until the client sends another request.
So if I wanted to make an html button that changed something on the page how would I send that response back to bottle.py regenerate the page with the change?
It depends on what you want to change...
For example, pushing the button could trigger a new HTTP request, you should then define a new feature in your code.
Let's take the previous example, and imagine you want to add a switchOff button.
You have to add the following button somewhere in the gpio.tpl :
<input type="submit" class="btn" name="LedsOff" value="Turn off the leds!">
Then, modify the function gpio() to add a new condition with the following :
elif request.GET.get('LedsOff','').strip():
from quick2wire.gpio import Pin, exported
with exported(Pin(12, Pin.Out)) as out1, exported(Pin(13, Pin.Out)) as out2:
out1.value = 0
out2.value = 0

How to make almost static site in Pyramid?

I'm switching to Pyramid from Apache/PHP/Smarty/Dreamweaver scheme.
I mean the situation of having static site in Apache with menu realized via Dreamweaver template or other static tools. And then if I wanted to put some dynamic content in html I could make the following:
Put smarty templates in html.
Create php behind html with same name. Php takes html as template.
Change links from html to php.
And that was all.
This scheme is convenient because the site is viewable in browser and editable
in Dreamweaver.
How can I reproduce this scheme in Pyramid?
There are separate dirs for templates and static content. Plus all this myapp:static modifiers in hrefs. Where to look up?
Thank you for your advices.
There is no smarty port for Python. So you would have to start using another template syntax, such as mako or chameleon
To do this, you would setup your view_config to respond to the url, end tell it to use the corresponding template.
If you want to do this, you would simple change your code. But this is not necessary, pyramid will process your requests, whether the url contains .html, .php, .python, /, or whatever.
You could still edit the templates in Dreamweaver I guess.
Only really static pages would be linked using static_url. If it is html that you mean to make into a template, it might be easiest to just start of with a template right away, without any dynamic content in it.
This is from the URL dispatch tutorial:
# in views.py
#view_config(route_name='view_page', renderer='templates/view.pt')
def view_page(request):
return {}
# in __init__.py
config.add_route('view_page', 'mypage.html')
You can build a small web application which uses traversal to serve html documents from a directory. Here's more explanations about how traversal works.
Then you can programmatically render those documents as Chameleon templates, using PageTemplateFile for example. This would allow you to include, say, common header/footer/navigation into every page.
This would mean that every page in your site will be in fact dynamic, so that would incur a small performance penalty for every page regardless of whether it has dynamic content or not, but you should not be concerned with this unless you're building the next Facebook. :) However, this approach would allow you to have a plain html document corresponding to every page in your website which you'll be able to edit using Dreamweaver or any other editor.
This is somewhat a different answer than ohters but here is a completely different flow.
Write all your pages in html. Everything!!! and then use something like angularjs or knockoutjs to add dynamic content. Pyramid will serve dynamic content requested using ajax.
You can then map everything to you html templates... edit those templates wherever you want since they are simply html files.
The downside is that making it work altogether isn't that simple at first.

Django & AJAX Changing Div Contents

My website have submenus for sections. What I want to do is, when users click the submenu, the content changes accordingly. For example, if user clicks "Pen", the contents of the shall be list of pens, clicks "Eraser" , contents shall be eraser list.
How can I achieve this by using Django template and ajax? I know that I could retrieve the information as JSON data and parse it to update the div, but that requires a lot of work and I cannot use the Django template functionality.
I managed to pass the AJAX request to the server and process the list, but how can I return the rendered template as AJAX result?
Simply return the rendered template fragment. You don't need to do anything special. Your Javascript can then just insert it into the DOM at the relevant point.

Categories