0

I've recently started learning how to use Django and I was wondering whether or not you could create a button in HTML that can directly call a python function without changing the URL. I was told this was possible with JS but I wanted to know if you could do that in Python.

Thanks for your time reading this!

2 Answers 2

1

A potential option if you're not ready to dig deep into javascript is to look into HTMX.

You can just create a django view with whatever python functionality you want, and use HTMX to perform a get or post call to it. Here I'm just returning a chunk of html that will be inserted into the dataLocation div, but you could literally call anything that's possible with python from your view and return useful html.

index.html

<button hx-get="/alert_message/" hx-target="#dataLocation" hx-swap="innerHTML">
    Click Me
</button>

<div id="dataLocation"></div>

views.py

from django.http import HttpResponse


def alert_message(request):
    return HttpResponse(
            (
                "<div class='alert alert-warning'>"
                "    <strong>Warning!</strong> Some important message."
                "</div>"
            ),
            status=200,
            content_type="text/html",
        )

urls.py

urlpatterns = [
    path('alert_message/', views.alert_message, name='alert_message'),
]
Sign up to request clarification or add additional context in comments.

Comments

0

Depending on your application you may want to look into Django forms. Otherwise JS (ajax) is the way to go. More details could always help.

1 Comment

hey mate, Thanks a lot for the response! I will look into using Django forms. My issue is that I simply don't like the idea of a url change on a button click to print Hello World for example!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.