Hobbyist here. Can't seem to figure out how to use the {% url %}
static template with dynamic javascript.
For example, I am creating a list of days for a calendar where each day when clicked on should pull data from the database based on its date.
The day is being created dynamically in a loop, where the href
attribute is being set for the URL.
My <a href>
in the JS code looks like this currently for setting the URL:
aLink.setAttribute('href', currentYear '-' (currentMonth 1) '-' dayCounter)
The problem with this method is this - Take a quick look at my URLS.py
urlpatterns = [
path('<int:tutor_id>', views.tutorHomeOverviewPage, name='tutorHomeOverviewPage'), #homepage for when tutor/customer signs in
path('<int:tutor_id>/<slug:selected_date>', views.tutorSelectedDay, name='tutorSelectedDay')
]
If I start off on a page which matches path 1 like so:
http://127.0.0.1:8000/tutorhomepage/7`
The code for the list item looks like this and doesn't point to a matching path because it removes the /7
from the URL:
<a href="2022-10-17" id="day17">17</a>
Path:
http://127.0.0.1:8000/tutorhomepage/2022-10-14
Giving me the obvious error when I click on it:
Using the URLconf defined in sass_language_tutor_app.urls, Django tried these URL patterns, in this order:
tutorhomepage/ <int:tutor_id> [name='tutorHomeOverviewPage']
tutorhomepage/ <int:tutor_id>/<slug:selected_date> [name='tutorSelectedDay']
admin/
The current path, tutorhomepage/2022-10-7, didn’t match any of these.
Now if I manually enter into the URL bar 7/
, before the date it works and the clicks match the second path and don't get rid of the 7/
.
No idea why this issue is occurring or how to fix it.
I want to use the {%url template%} which works when I make a static LI in the html file like so:
<a href="{% url 'tutorhomepage:tutorSelectedDay' tutor_id='7' selected_date='2022-10-16'%}">Date check test - click here</a>
The problem is when I try to do that in the JS file, it adds % signs and ampersands and makes the URL something its not. Making no path match.
Any idea of what is happening in this situation and what a possible solution could be?
Any help would be much appreciated, thanks!
CodePudding user response:
In your url <slug:selected_date>
you are telling Django that the url should contain a Slug and the date is not a slug, you are passing it as string so you need to make like this:
urlpatterns = [
path('<int:tutor_id>', views.tutorHomeOverviewPage, name='tutorHomeOverviewPage'), #homepage for when tutor/customer signs in
path('<int:tutor_id>/<str:selected_date>', views.tutorSelectedDay, name='tutorSelectedDay')
]