When jsevent triggered , it forwards link parameter to data-url attribute of a button and when user click that button it redirects to django backend view but there is a problem with parsing line of JS
$('#btn_del').attr('data-url',{% url 'event_delete' + event.id + %});
is there any chance to combine that syntax ?
Thank you , have a nice days.
JS:
eventClick: function(event, jsEvent, view) {
$('#modalTitle').html(event.id);
$('#btn_del').attr('data-url',`{% url 'event_delete' ` + event.id + `%}`);
$('#calendarEditModal').modal();
console.log(event.id);
}
url.py
....
url(r'^event/(?P<pk>\d+)/delete/$', event_delete, name='event_delete'),
....
Html button that redirects to django
<button id="btn_del" type="button" class="btn btn-primary js-delete-events" data-url="">
<span class="glyphicon glyphicon-pencil"></span>
Edit
</button>
Result should be like this format event.pk is going to be our parameter numeric value , it's ok.
<button type="button" class="btn btn-primary js-delete-events" data-url="{% url 'event_delete' event.pk %}">
<span class="glyphicon glyphicon-plus"></span>
button
</button>
/event/1/update/ is the last result of seen from browser inspect. But I need to write inside jsEvent with django syntax to able to reach backend view which is {% url 'event_delete' event.pk %} something like that.
No, it cannot be done that way... Parsing of your templates (the {% url %} tag) is done on the server before even the browser receives anything. Browser doesn't know what template tags are you using.
On the other side, JavaScript is executed in the browser, so template language has also no knowledge about variables inside it.
Solution for that is to use a package like Django JS Reverse. The second one is to pass full URL to the JavaScript, just like it receives the ID of the item.
Related
I am developing on localhost: http://127.0.0.1:8000
When I perform some search on the website, I want that if the query does not return results, the New entry button allows the creation of a new article from what has been searched in the search input.
So if I search 'whatever' and there is no article called 'whatever', the button should redirect me to the creation page of the article 'whatever'.
<script>
$( document ).ready(function() {
var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}";
document.getElementById('newEntrybtn').setAttribute('href',newEntryUrl);
});
</script>
{% for article in articles %}
{% block wiki_search_loop2 %}
{% endblock %}
{% empty%}
There is no page created for '{{ search_query }}', would you like to create a page nowee?
<a class="btn btn-success" id="newEntrybtn" role="button"><i class="fa fa-plus" aria-hidden="true"></i> New entry ({{ search_query }})</a>
{% endfor %}
To calculate the url to create the new article, I use this line:
var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}";
If I do an alert(newEntryUrl); it returns the desired result: 127.0.0.1:8000/wiki/_create/?slug=whatever
However, if I click the newEntrybtn button, it redirects me to the following url: http://127.0.0.1:8000/wiki/_search/127.0.0.1:8000/wiki/_create/?slug=whatever
Which is strange to me since at no time have I assigned the href attribute to the button, much less have I assigned it any value. It seems that somehow, by default, it gets the value of the current page.
My question is, how can I remove the current page: http://127.0.0.1:8000/wiki/_search/ so that the button href just has this structure: 127.0.0.1:8000/wiki/_create/?slug=whatever ?
I think you are appending the value twice. Once when the page loads because it is in the document.ready function and once again when the button is clicked. Try writing it in another function and calling the function when the button is clicked.
setAttribute is being called twice
https://codepen.io/sijbc/pen/zYNdrmz
.setAttribute() is being called twice
function createUrl(){
var newEntryUrl = window.location.hostname+":8000/wiki/_create/?slug="+"{{ search_query }}";
var newEntryBtn = document.getElementById('newEntrybtn')
newEntryBtn.addEventListener("click" function(){
newEntryBtn.setAttribute('href',newEntryUrl);
})
The problem is because you are using a relative URL as the href, causing the browser to append this to the current URL you are looking at.
In your example, your button will be set as follows:
<a class="btn btn-success" id="newEntrybtn" role="button" href="127.0.0.1/...">
And clicking on it will append the href to the current URL since the browser will consider it as a resource of the current page.
Following your example, using an absolute URL will allow you to go directly to the URL as you have it set as long as you know the full structure (in your case, you are missing the protocol/scheme):
<a class="btn btn-success" id="newEntrybtn" role="button" href="http://127.0.0.1/...">
Or ideally you should use a relative URL by defining correctly the segment of the URL it represents (defining the path from your host where the resource is located):
<a class="btn btn-success" id="newEntrybtn" role="button" href="/wiki/_create/...">
(notice how the URL starts with a slash and omits the server host and protocol).
It is preferred in most cases to use relative URLs to make your code run regardless of the server (environment), meaning it will always use the same server or protocol of the current URL. But it's up to you based on your needs.
References:
https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_is_a_URL#absolute_urls_vs_relative_urls
I found a good solution without using JavaScript, in just one line of code:
<a class="btn btn-success" href="/wiki/_create/?slug={{ search_query }}" role="button"><i class="fa fa-plus" aria-hidden="true"></i> New entry ({{ search_query }})</a>
Thanks to those who have posted an answer, you have inspired me a lot.
I need to redirect to new window by using onclick openNewWindow . I just route to my controller but seems it give error as "Route [sla.slaCategoryTreeListScreen] not defined"
Here is my controller code.
public function slaCategoryTreeListScreen() {
return view('sla.slm.SLACategoryCheckBoxList');
}
my view onclick part
<a class="btn btn-sm btn-default pull-right" type="button" title="Search Category" onclick="openNewWindow('{{ route('sla.slaCategoryTreeListScreen') }}" >
my route
Route::group(['prefix' => 'sla'], function () {
Route::resource('sla', 'SlaController');
//Route::get('sla','SlaController#slaCategoryTreeListScreen')->name('SlaController.slaCategoryTreeListScreen');
// Route::get('sla','SlaController#SlaCategoryTreeListScreen')->name('sla.SlaCategoryTreeListScreen');
Route::get('sla/getbranch/{id}','SlaController#getBranchAjax')->name('sla.getBranchAjax');
Route::get('sla/getBranchAjax2/{cuid}/{stid?}','SlaController#getBranchAjax2')->name('sla.getBranchAjax2');
});
The comment part on route that are trying was not fix at all..Sorry for my bad English and i hope its help.
First of all: Route::resource() does only register routes by a predefined array of defaults ('index', 'create', 'store', 'show', 'edit', 'update', 'destroy').
It will not automatically register any method from your controller.
Also make sure that your controller has methods for all these routes or specify a subset of routes. Check this for more information: https://laravel.com/docs/6.x/controllers#restful-partial-resource-routes
Second: Your a-tag seems to be malformed. The JavaScript method opens with (' but is never closed again. So it should be like this:
onclick="openNewWindow('{{ route('sla.slaCategoryTreeListScreen') }}')"
To simply open the URL in a new tab you could use this (with target="_blank"):
Search Category
Additionally: make sure that a route named sla.slaCategoryTreeListScreen exist. Easiest way to do so is by listing all available routes by running the command php artisan route:list from the root directory of your project in a terminal.
Replace this in your view file
<a class="btn btn-sm btn-default pull-right" type="button" title="Search Category" onclick="window.open('{{ route('sla.SlaCategoryTreeListScreen') }} ', '_blank')" >
Right now I am making a MVC that has a default page that loads up. From this page, the user can press a button to go to the next page. So far, I have made the first page work and a button that goes to a specified URL for the second page. The only issue I am having is making the view that I want to correspond to the second page have the correct URL.
Here is the code for my button link to the next URL
<input type="button" value="Create" onclick="location.href='#Url.Action("IndexA", "HomeController")'" />
I guess my question is how do I make my view have the specified URL that I want so it can be accessed?
I used something like this in my own project.
#if (Request.UrlReferrer != null && Request.UrlReferrer.Host == Request.Url.Host)
{
<a href="#Request.UrlReferrer" class="dbtn btn-11">
<i class="fa fa-undo"></i>
#Resources._Action_Back
</a>
}
only came from within the domain that was published I said let the button appear.
there is something like add controller in default settings controller name + controller. So just write the name there.
I had to put "home" in the URL.Action instead of "HomeController"
Please see this photo.
https://ibb.co/4SS5nYh
You add a new controller and a new view for that new page (also a model). I have called mine Test.
Then in the button. you call them with url action.
<input type="button" value="Create" onclick="location.href='#Url.Action("Index", "Test")'" />
In my django project i have to rendere a var ina template as html.
I do this in my view:
con_stat = "<div id='overlay_demo' style='display:block'><div id='text-demo'><div class='login-box-body'><p class='login-box-msg'><strong><font color='red'>MY TITLE HERE</font></strong></p><br>My text here<br><br><div><form><button onclick='location.href=https://mywebsite.com/contact;' class='btn btn-block btn-danger btn-lg'>REPORT THE PROBLEM</button><br><a href='/register/retry'><button class='btn btn-block btn-success btn-lg'>RETRY THE REGISTRATION PROCES</button></a></form></div></div></div></div>"
context_dict = {'all_case': test_case, 'all_set': sg, 'the_stat': con_stat}
response = render(request, b_temp, context_dict, context)
well, at this point in my html template:
{% autoescape off %}{{ the_stat }}{% endautoescape %}
or also i try:
{{ the_stat|safe }}
template now display html correctly but the problem is the link, not my first button (with onclick= function) nor second one (with a href link) works.
In every case when i click the behaviour is to reload the same page.
Someone had experienced some problem related to link,javascript call in django template render like that above?
So many thanks in advance
Try this
onclick="javascript:location.href='https://mywebsite.com/contact'"
Clarification:
I really don't want to embed my js in my html. The suggestions I'm
getting, like, this or that post might contain the possible answer,
well in those answers, they embedded their js in html. Both my
js and html is large. So embedding will surely make them messy and
hard to debug
In my project there's a module where user can see details about product and add products to cart. For this he needs to specify the number of products he wants to add. It looks like
For this I have a + and - icon. I have a js file where it increments or decrements each time + or - has been clicked.
Now, what I want is this:
A user can add products but if the total number exceeds the number of
products stored in the database, he can't add products even if he
click the + button. For example, if there are 4 items and he clicked
5 times then on the 5th click the amount will remain 4, won't
increase.
So I need a django variable in my js file. I looked up how to do that, and I found some solutions.
Some solution says var data = '{{data|escapejs}}' this while some solution says
<script>
var myTable = {% autoescape off %}{{ table_data }}{% endautoescape %};
</script>
But I don't want to embed js on my html like this. Here is my js file:
function incrementValue()
{
var value = parseInt(document.getElementById('quantity').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('quantity').value = value;
}
And my html, from where I am calling this js like this:
<span class="btn btn-default btn-lg btn-qty" onclick="incrementValue()">
<span class="glyphicon glyphicon-plus" aria-hidden="true">
</span>
</span>
<input class="btn btn-default btn-lg btn-qty" id="quantity" value="0" />
<span class="btn btn-default btn-lg btn-qty" onclick="decrementValue()">
<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>
</span>
</span>
What is the best way to pass django variable to js or, How should I pass the django variable to my js so that there will be no vulnerability or no security issues and also I don't want to embed js in my html.