HTMX websockets extension doesn't connect to Django channels - python

I try to connect a Django channels Consumer to a HTMX ext-ws element, but I can't get a step further.
class MessageConsumer(WebsocketConsumer):
def connect(self):
self.accept()
print("connect")
#self.send(
# "type": "websocket.send",
# "text": "..."
#)
...
<head>
...
<script src="{% static 'common/js/htmx/htmx.min.js' %}" defer></script>
<script src="{% static 'common/js/htmx/ext/ws.js' %}" defer></script>
...
</head>
...
The HTMX.js and the ws.js gets loaded correctly at the client's browser.
<div id="messages-container"
hx-ws="connect:/ws/messages/"
{# hx-ext="ws" ws-connect="/ws/messages/" does not work at all #}
>
<div id="message"></div>
</div>
If I use the old HTMX-builtin hx-ws method, at least the websocket connects. But I can't get a message to the HTMX element (I thought the #message div should be replaced).
If I use the new-style (HTMX extension) syntax (hx-ext="ws" ws-connect...)
Can anyone point me to the right direction?

As per docs you need to also include hx-swap-oob="true" attribute into the html that you send back from websocket:
See example from htmx GH:
https://github.com/bigskysoftware/htmx/blob/master/test/servers/ws/server.go#L24
When using the plugin version, what worked for me was removing the defer attribute from htmx related script tags.
Not sure why including defer is causing the issue though.
Update:
A GH issue has been opened by OP:
https://github.com/bigskysoftware/htmx/issues/957

Related

How do you input and output text with Pyscript?

I’m learning py-script where you can use <py-script></py-script> in an HTML5 file to write Python Code. As a python coder, I would like to try web development while still using python, so it would be helpful if we could output and input information using py-script.
For example, could someone explain how to get this function to work:
<html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<div>Type an sample input here</div>
<input id = “test_input”></input>
<-- How would you get this button to display the text you typed into the input into the div with the id, “test”--!>
<button id = “submit-button” onClick = “py-script-function”>
<div id = “test”></div>
<div
<py-script>
<py-script>
</body>
</html
I would appreciate it and I hope this will also help the other py-script users.
I checked source code on GitHub and found folder examples.
Using files todo.html and todo.py I created this index.html
(which I tested using local server python -m http.server)
Some elements I figured out because I have some experience with JavaScript and CSS - so it could be good to learn JavaScript and CSS to work with HTML elements.
index.html
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />-->
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<div>Type an sample input here</div>
<input type="text" id="test-input"/>
<button id="submit-button" type="submit" pys-onClick="my_function">OK</button>
<div id="test-output"></div>
<py-script>
from js import console
def my_function(*args, **kwargs):
#print('args:', args)
#print('kwargs:', kwargs)
console.log(f'args: {args}')
console.log(f'kwargs: {kwargs}')
text = Element('test-input').element.value
#print('text:', text)
console.log(f'text: {text}')
Element('test-output').element.innerText = text
</py-script>
</body>
</html>
Here screenshot with JavaScript console in DevTool in Firefox.
It needed longer time to load all modules
(from Create pyodine runtime to Collecting nodes...)
Next you can see outputs from console.log().
You may also use print() but it shows text with extra error writing to undefined ....
An alternative to way to display the output would be to replace the
Element('test-output').element.innerText = text
by
pyscript.write('test-output', text)

Error 404 - Getting Stylesheet Working in Bottle (Python Webframework)

I'm using bottle (the python webframework) to familiarize myself with html, js and css and using localhost to access the site. I can't quite get the css file to be applied to the site that the templates link to. Sometimes it works, but when I edit the file, it doesn't update and even loses the file and can't find it, even after restarting the server. The Console gives the 404 error (file not found), even though I have not moved it.
I first noticed the issue when the CSS wouldn't update in the browser when I refreshed. After clearing out the cache every time I edited, I found the 404 not found issue. I've validated the css file to check if a synthax error was the issue. It came back clean. I redownloaded the bottle.py file in case it needed an update. Still the same result. I also triple checked the link path, even tried to put them all into the same folder with no change.
Here is my file structure:
project folder
static
css
main.css
views
home.tpl
bottle.py
server.py
start.bat (starts the server)
Here is the code in server.py
from bottle import route, run, template
#route('/')
def home():
return template('home')
run(host='localhost', port=8080, debug='True', reloader='True')
Here is the template home.tpl:
<!DOCTYPE html>
<html>
<head>
<title>Bottle Site</title>
<link rel="stylesheet" type="text/css" href="/static/css/main.css" />
</head>
<body>
<div id="wrapper">
<div id="header">
<h1>Header!</h1>
</div>
<div id="navigation">
<ul>
<li>Home</li>
</ul>
</div>
<div id="section">
Section text!
</div>
<div id="footer">
© 2019 - <b href="#" id="dev">Footer/b>
</div>
</div>
</body>
</html>
I'd like to reliably be able to apply the css to the site without it crashing and sometimes not finding the file. Whenever I paste a fresh copy of my css file and start the server, it works fine until I try and change the file (a background color, for example. Nothing syntax breaking) but it doesn't update. when I clear the cache, it turns into a plane html file and the console reads:
"GET /static/css/main.css HTTP/1.1" 404 764
I just figured it out.
In the server.py file, you apparently need a:
#route('/static/<filename:path>')
def send_static(filename):
return static_file(filename, root='./static/')
to give the server a route that it can access and find the files (i think).
So in the templates, to show it where they are, you can say:
<link rel="stylesheet" type="text/css" href="/static/css/main.css" />
And it will work fabulously every time. :)
Why without the route it sometimes found the file and sometimes not will forever be a mystery of computer science.
Routes are hard.
Have a nice day! :)
I also like to use whitenoise with bottle.
from whitenoise import WhiteNoise
...
botapp = WhiteNoise(botapp)
botapp.add_files(staticfolder, prefix='static/')

Returning a static HTML file with # fragment pointing to an <section> element

Say a website www.example.com has a with id="section_two". This section is offscreen. I can make this website load with this section onscreen by calling the URL www.example.com#section_two.
Now, say I'm trying to return a static index.html file using Bottle.py, but specifically I'm trying to return it with a onscreen that would otherwise offscreen. How can I return a URL of the form www.example.com#section_two?
Do you mean that you want a user to receive a html page already scrolled to the necessary section? It is not possible without some in-browser JavaScript. You can add something like this to your html (with JQuery):
<head>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(function() {
$('#section_two').get(0).scrollIntoView();
});
</script>
</head>

Recaptcha 2 (a.k.a. nocaptcha) doesn't load on Internet Explorer 8 on first load

I am using new recaptcha2 and everything seems to work flawlessly on all modern browsers, however I have a problem only with IE8.
Captcha load properly on second and next visit on the page, but never on first load or in Private Mode.
What is even more strange, google recaptcha 2 page demo doesn't have this problems. I am using django-nocaptcha-recaptcha package, which is based on recaptcha-client for python, so I believe my configuration is pretty standard.
Console doesn't show any errors. Divs are not populate by recaptcha code.
Google on their recaptcha2 developers guide suggest to use a snipet like this:
<html>
<head>
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="your_site_key"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
django-nocaptcha-recaptcha use similar piece of code and also use a line like this:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
This suppose to cause a problem, since ascync and defer are supported in IE 10+. In my case, when I used:
<script src="https://www.google.com/recaptcha/api.js"></script>
Problem disappeared :)

django : using admin datepicker

I'm trying to use the admin datepicker in my own django forms.
Roughly following the discussion here : http://www.mail-archive.com/django-users#googlegroups.com/msg72138.html
I've
a) In my forms.py included the line
from django.contrib.admin import widgets
b) and used the widget like this :
date = forms.DateTimeField(widget=widgets.AdminDateWidget())
c) And in my actual template I've added :
{{form.media}}
To include the js / styles etc.
However, when I try to view my form I get no nice widget; just an ordinary text box. And the Firefox javascript error console shows me :
gettext is not defined in calendar.js (line 26)
and
addEvent is not defined in DateTimeShortcuts.js (line 254)
Any suggestions? Is this a bug in Django's own javascript library?
Update : Basically, need to include the core and (or fake) the i18lization
Update 2 : Carl points out this is pretty much a duplicate of Using Django time/date widgets in custom form (although starting from a different position)
No, it's not a bug.
It's trying to call the gettext() internationalization function in js. You can do js internationalization much like you do it in python code or templates, it's only a less known feature.
If you don't use js internationalization in your project you can just put.
<script>function gettext(txt){ return txt }</script>
in your top template so the js interpreter doesn't choke.
This is a hacky way to solve it I know.
Edit:
Or you can include the exact jsi18n js django admin references to get it working even with other languages. I don't know which one it is.
This was posted on django-users today:
http://groups.google.com/group/django-users/browse_thread/thread/2f529966472c479d#
Maybe it was you, anyway, just in case.
I think I solved the first half by explicitly adding these lines to my template :
<script type="text/javascript" src="../../../jsi18n/"></script>
<script type="text/javascript" src="/admin_media/js/core.js"></script>
<script type="text/javascript" src="/admin_media/js/admin/RelatedObjectLookups.js"></script>
But it still reports not knowing gettext
You may find the following works for you:
<link href="/media/css/base.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/media/js/core.js"></script>
{{ form.media }}

Categories

Resources