Issue
Getting this error Could not parse the remainder: '(module.url)' from 'call_url(module.url)'
in Django template calling a method call_url
with argument from HTMX request.
<p>
<span class="fw-semibold">URL:</span> {{ module.url }}
<span class="ms-3" hx-get="{{ call_url(module.url) }}" hx-swap="innerHTML">Check URL response</span>
</p>
I also tried with no square brackets {{ call_url module.url }}
, but it did not help
Method call_url is passed to context:
async def get_project(request, project_id: int):
"""Detailed project view with modules."""
project = await Project.objects.prefetch_related("modules").aget(pk=project_id)
return render(
request,
"monitor/project.html",
context={"project": project, "call_url": call_url},
)
async def call_url(url: str):
"""Make a request to an external url."""
# TODO: add headers to aiohttp.ClientSession
async with aiohttp.ClientSession() as session:
async with session.get(url=url) as response:
response_code = response.status
if response_code == 200:
return HttpResponse(content="Page response OK", status=200)
else:
return HttpResponse(
content=f"Error. Response code id {response_code}",
status=response_code,
)
Tried to pass url directly to async def call_url(url: str = "https://www.google.com"):
and call it from template hx-get="{{ call_url }}"
but I get an error:
Not Found: /project/1/<coroutine object call_url at 0x000001A3A95AA940>
[02/May/2023 22:02:02] "GET /project/1/%3Ccoroutine%20object%20call_url%20at%200x000001A3A95AA940%3E HTTP/1.1" 404 3710
What am I doing wrong?
Solution
You need to create an URL for the endpoint with url
template tag passing module.url
as an argument. Assuming the urls.py
looks something like this:
from django.urls import path
import myapp.views
urlpatterns = [
path("call/<str:url>/", myapp.views.call_url),
...
]
In the template:
hx-get="{% url 'call' module.url %}"
Note: you may have to apply urllib.parse.unquote
to decode the URL string.
Answered By - Dauros
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.