31๐
I think the best way to do this is to create a html data-*
attribute with the URL rendered in a template and then use javascript to retrieve that.
This way you avoid mixing js/django template stuff together. Also, I keep all of my JS in a separate file outside the view (which is a much better practice in general), and therefore trying to mix these two wonโt work.
For instance, if you have a url you want, just create an html hidden element:
<input type="hidden" id="Url" data-url="{% url 'myapp:productdetail' id %}" />
Then, in your JS:
$(document).on('click', '.alink', function () {
var url = $("#Url").attr("data-url");
});
I frequently use this pattern for dropdown lists so that I donโt have to serve all of the options when I first render the page (and this usually speeds it up).
22๐
You are trying to access javascript variable that is created at user click on frontend within your Django template at the backend. But, you already know that it would not work.
A better option would be to reconstruct the url in javascript:
$(document).on('click', '.alink', function () {
// Generate URL without "id" bit
var url = "{% url 'myapp:productdetail' %}";
var id = $(this).attr('id');
// Construct the full URL with "id"
document.location.href = url + "/" + id;
});
If you donโt have a django url helper that would return a URL that you need, you can print out just any and simply replace it in javascript like so:
$(document).on('click', '.alink', function () {
var url = "{% url 'myapp:productdetail' 123 %}";
var id = $(this).attr('id');
// Construct the full URL with "id"
document.location.href = url.replace('123', id);
});
- Login_required decorator on ajax views to return 401 instead of 302
- Django Postgres ArrayField vs One-to-Many relationship
- Django: admin interface: how to change user password
6๐
The problem seems to be in that you using django template language in js static file(am i right?)
Try to move that variable to html template file, ex:
<script type=text/javascript>
var a = "{% url'myapp:productdetail' id %}" </script>
And in static js file:
document.location.href = a;
- Does Django have a Windows 7 Installer? I couldn't find one and theres little mention of Windows
- Django AttributeError 'tuple' object has no attribute 'regex'
- Pylint recursively for a given filename
- Correct way of transaction.rollback() with raise exception in django
- Django/celery โ celery status: Error: No nodes replied within time constraint
-1๐
You can use javascript code " window.location.origin " , this will give base url and after that you can add "/pathname"
- Disable prefers-color-scheme: dark in django admin
- Django 1.3 logging: 500 errors are not logged
- Can I slow down Django
-1๐
You donโt need to pass any of thatโฆ
Write.
location.href = "/" + id
Thatโs all.