let's say one of my urlpatterns looks like this.
url('^objects/update/(?P<pk>\d+)$', views.UpdateView.as_view(), name = 'update-object'),
I need to redirect user to the update page depending on the selected object (the list of objects is populated using Ajax). So I'd like to pass that named url pattern to the JavaScript, in order to build the actual url on the client side.
Example of what I want to achieve:
pass the name 'update-objects' to the function
get the actual url pattern, replace (?P<pk>..) with {pk}
pass the result to the javascript, resulting in : objects/update/{pk}
any tips?
thanks
to make it more clear: at the moment of rendering, I can't do url reverse because the PK is not known yet. I need to make kind of javascript-urlpattern which will later be converted to the real url (i.e. my JS code will replace {pk} part with the actual pk value)
The actual URL reversing must happen on the server side. There are several ways to do this, and the most elegant of these probably depends on how exactly your script and markup are set up for this. One thing I've done recently is to attach the URL to a logical element using HTML5 data attributes, which are easy to retrieve using jQuery. If you're not using jQuery, I'll leave it up to you to translate to pure JS. You haven't provided any code or specifics for your client-side, so I'm kind of shooting in the dark here, but maybe this will give you the idea:
Django HTML template:
<ul class="object-list">
{% for object in objectList %}
<li data-update-url="{% url update-objects object.pk %}">object.name</li>
{% endfor %}
</ul>
JS:
$('.object-list').on('click', 'li' function () {
var updateUrl = $(this).data('update-url')
...
});
It sounds like you need to make an additional ajax call once the object has actually been selected. Don't try and second guess your url.conf by trying to work out the url on the client side - you'd just be making trouble for yourself later. Wait till you can get a pk, then use django's reverse function to give you your url (doing anything else violates DRY).
How about creating a simple view that returns the url -
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseBadRequest
def get_url(request):
if request.is_ajax() and request.method == 'POST':
obj_id = request.POST['obj_id']
url = reverse('object-update', kwargs{'pk': obj_id})
return HttpResponse(obj_id)
return HttpResponseBadRequest()
Then write a javascript function that gets the url using an ajax call to your new view and then redirects. You'd call this function as soon as the object's been selected. I would suggest using JQuery to do this, pure javascript will require you to write more code, and probably write browser specific code (depending on your target). Also it supports dealing with django's csrf protection (you'll need to implement this for ajax calls if you haven't already).
var redirect = function(obj) {
$.ajax({
url: '/your-get-url-view/',
method: 'post',
data: {'obj_id': obj},
success: function(url){
window.location = url;
}
});
}
I'm afraid I don't know how you're getting from the selected object to the pk (For simplicity I've assumed it's available to the redirect function) - you may have to do some processing in the view to get there.
I haven't tested the above code, but it should give you an idea of what I'm suggesting.
Try this one:
Reverse method for generating Django urls
https://github.com/mlouro/django-js-utils
One more
https://github.com/Dimitri-Gnidash/django-js-utils
If you have a URL that only has one PK field in it, you could resolve it with any number (e.g. 0), then substitute the number as required.
In my scenario my URL had a pk then an upload_id, so I had to replace on the right most instance of a 0, with <upload_id>, which the JS would replace this string occurance as required:
detele_url_upload_id_0 = reverse(f'{APP_NAME}:api_upload_delete', args=[pk, 0])
prefix, suffix = detele_url_upload_id_0.rsplit('0', 1)
context['generic_delete_url'] = prefix + '<upload_id>' + suffix
Then in the JS:
const deleteUrl = genericDeleteUrl.replace('<upload_id>', uploadId)
Related
I am building a web app and I am using Firebase to store my user's data in Cloud Firestore. There is a page on my web app that allows users to view their documents from Cloud Firestore. I would like to add a query parameter to the end of my URL on view.html so I can take that query parameter value and use it to search for a document.
I have been searching online to find possible solutions. So far I have come across a few videos on the topic, but they haven't been going into the depth I have been needing. For example, this video shows how to add and get query parameters from a URL, but it only shows how to log those changes in the console. How would I make that my URL?
I've also be browsing Stackoverflow for solutions. This Stackoverflow post asks a similar question, however, many of the solutions in the answers causes view.html to reload on a loop. Why would this be, and if this is a possible solution, how would I stop this from happening.
How would I go about appending and fetching URL query parameters in Javascript?
You say you want to do this in javascript, so I assume the page itself is building/modifying a link to either place on the page or go to directly via javascript.
In javascript in the browser there is the URL object, which can build and decompose URLs
let thisPage = new URL(window.location.href);
let thatPage = new URL("https://that.example.com/path/page");
In any case, once you have a URL object you can access the parts of it to read and set the values.
Adding a query parameter uses the searchParams attribute of the URL, where you can add parameters with the .append method — and you don't have to worry about managing the ? and & … the method takes care of that for you.
thisPage.searchParams.append('yourKey', 'someValue');
This demonstrates it live on this page, adding search parameters and displaying the URL at each step:
let here = new URL(window.location.href);
console.log(here);
here.searchParams.append('firstKey', 'theValue');
console.log(here);
here.searchParams.append('key2', 'another');
console.log(here);
I have solved this issue in the simplest way. It slipped my mind that I could link to view.html by adding the search parameter to the URL. Here's what I did:
On index.html where I link to view.html, I created the function openViewer();. I added the parameter to the end of URL href.
function openViewer() {
window.location.href = `view.html?id={docId}`;
}
Then on view.html, I got the parameter using URLSearchParameters like so:
const thisPage = new URL(window.location.href);
var id = thisPage.searchParams.get('id');
console.log(id)
The new URL of the page is now "www.mysite.com/view.html?id=mydocid".
You can try to push state as so in the actual view.html
<script>
const thisPage = new URL(window.location.href);
window.history.pushState("id","id",thisPage);
</script>
I am working inside a jquery, getJSON callback function using flask as my web framework.
I am trying to set the link desination for a dynamically created dom element. I want to set it to the jinja2 code for url_for. So, I would like to do something like this:
a.href ="{{ url_for('write_response', id=".concat(data.libArticles[i].id.toString(), ") }}");
I have had the worst time doing this. First, it would not recognize the "{{" and "}}" strings, removing them, opening quotes and doing other weird stuff because of those characters. Finally, by doing this:
var url1 = "{url_for('write_response', id=".concat(data.libArticles[i].id.toString(),")}");
var url2 ="{".concat(url1, "}");
a.href = url2;
it finally accepted the string with two instances of "{", so it accepted "{{somethig}}"
This still did not work and instead, when the link is clicked, it redirects to the following and fails :
http://localhost:5000/write_response/%7B%7Burl_for('write_response',%20id=3)%7D%7D
Does anyone know how to do this?
Your mixing up your python and javascript. Your first attempt failed, because your trying to execute javascript inside python. What's actually happening is everything, including the ".concat is being treated as the value for your id. Your second attempt is even more confused.
It's worth remembering that the python code gets executed on the server and then sent to the browser, the javascript gets executed after the fact in the browser. So the python/jinja code can't possibly know about the value of a javascript variable.
I think you should be able to do something like the following to get it to work:
var url = "{{ url_for('write_response') }}";
var id = encodeURIComponent(data.libArticles[i].id.toString());
url += '?id='+id;
Everything inside the set of {{ }} is considered jinja code, seperate from whatever is going on around it in the file. this should translate into the following in the browser:
var url = "/write-response";
var id = encodeURIComponent(data.libArticles[i].id.toString());
url += '?id='+id;
which should get you something like /write-response?id=12345
The encodeURLComponent(..) call just makes sure the value is url safe.
I have looked at a number of answers and other websites, but none answer my specific question. I have a webpage with "+" and "-" buttons, which should increment a variable called "pieFact". This variable must be updated dynamically without having to refresh the page. It should then be passed to my Django view each time the value is changed. This will be used to update the size of pie charts in a web map. I have the following:
<button type="button" id=bttnMinus onclick="pieFact=pieFact*0.9">-</button>
<button type="button" id=bttnPlus onclick="pieFact=pieFact*1.1">+</button></td>
<script type="text.javascript">
var pieFact=0;
</script>
How can I pass the value of "pieFact" to Django? Based on my limited knowledge, I think I may have to use AJAX post/get.
In order to keep from refreshing the page, yes, you will need AJAX. I usually don't like to suggest libraries too much in answers, however, in the interest of being easily cross-browser compatible, I would suggest the use of jQuery.
With jQuery it would be as simple as
Inside of your django template
<html>
...
<head>
<script>
var URL = "{% url 'my_view_that_updates_pieFact' %}";
</script>
</head>
...
Later on...
You'll need to either POST or GET the data to the server via AJAX. To be more RESTful, whenever I need to send data to the server I use POST. jQuery provides the $.post() convenience function to AJAX data to a url via POST. The three parameters are the URL, the data to send (as a JavaScript object; think python dictionaries if you're not too familiar with JavaScript), and a callback function once the server sends back a response.
<script>
function updatePieFact(){
var data = {'pieFact': pieFact};
$.post(URL, data, function(response){
if(response === 'success'){ alert('Yay!'); }
else{ alert('Error! :('); }
});
}
The .click() functions are basically the same thing as specifying onlick in the html attribute. Both click events update pieFact as you would expect and then call updatePieFact() to send the value of pieFact to the server.
$(document).ready(function(){
$('#bttnMinus').click(function(){
pieFact *= 0.9;
updatePieFact();
});
$('#bttnPlus').click(function(){
pieFact *= 1.1;
updatePieFact();
});
});
</script>
In views.py
Since I've used the $.post() function in the JavaScript, the request that Django is going to receive is going to have a method of "POST", so I check to make sure that the method is indeed POST (this means that if someone visits the URL for this view with something like a GET request, they won't update anything). Once I see that the request is, in fact, a POST, I check to see if the key 'pieFact' is in the dict request.POST.
Remember when I set the variable data in the javascript to {'pieFact': pieFact}? That javascript just becomes the request.POST python dictionary. So, if in the javascript I had instead used var data = {'hello': pieFact};, then I would be checking if 'hello' in request.POST instead. Once I see that pieFact is in the request.POST dictionary, I can get its value and then do something with it. If everything is successful, I return an HttpResponse with the string 'success'. This correlates with the check in javascript: if(response === 'success').
def my_view_that_updates_pieFact(request):
if request.method == 'POST':
if 'pieFact' in request.POST:
pieFact = request.POST['pieFact']
# doSomething with pieFact here...
return HttpResponse('success') # if everything is OK
# nothing went well
return HttpRepsonse('FAIL!!!!!')
Hopefully that will get you pointed in the right direction.
I have built a calendar in php. It currently can be controlled by GET values from the URL. Now I want the calendar to be managed and displayed using AJAX instead. So that the page not need to be reloaded.
How do I do this best with AJAX? More specifically, I wonder how I do with all GET values? There are quite a few. The only solution I find out is that each link in the calendar must have an onclick-statement to a great many attributes (the GET attributes)? Feels like the wrong way.
Please help me.
Edit: How should this code be changed to work out?
$('a.cal_update').bind("click", function ()
{
event.preventDefault();
update_url = $(this).attr("href");
$.ajax({
type : "GET"
, dataType : 'json'
, url : update_url
, async : false
, success : function(data)
{
$('#calendar').html(data.html);
}
});
return false;
});
Keep the existing links and forms, build on things that work
You have existing views of the data. Keep the same data but add additional views that provide it in a clean data format (such as JSON) instead of a document format (like HTML). Add a query string parameter or HTTP header that you use to decide which view to return.
Use a library (such as YUI 3, jQuery, etc) to bind event handlers to your existing links and forms to override the normal activation functionality and replace it with an Ajax call to the alternative view.
Use pushState to keep your URLs bookmarkable.
You can return a JSON string from the server and handle it with Ajax on the client side.
I want to redirect after a successful ajax request (which I know how to do) but I want to pass along the returned data which will be used to load an iframe on the page I just redirected to.
What's the best way to pass such data along and use it to open and populate an iframe in the page I just redirected to?
EDIT:
I am passing a GET variable but am having to use the following to access it for use in my iframe src attribute:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
var d = $_GET('thedata');
I assume there isn't really a more straightforward way to access the GET vars?
If it's not too much data, you could pass it as a get parameter in the redirect:
document.location = "/otherpage?somevar=" + urlescape(var)
Remember that urls are limited to 1024 chars, and that special chars must be escaped.
If it is beyond that limit your best move is to use server side sessions. You will use a database on the server to store the necessary information and pass a unique identifier in the url, or as a cookie on the users computer. When the new page loads, it can then pull the information out of the database using the identifier. Sessions are supported in virtually every web framework out of the box.
Another alternative may be to place the data as a hidden attribute in a form which uses the post method (to get around the 1024 char limit), and simulating a submission of the form in javascript to accomplish the redirect, including the data.