Replace a html div based on .onchange, passing in a variable - javascript

I am using Flask and wtforms to create a web page "index.html" that loads multiple forms. The selection of forms that are rendered depend on dropdown selections, and a variable "serviceid" updated from an API call. The form selection and rendering is handled in an included file "form_select.html", which requires "serviceid" value to pick the correct form. I am having trouble figuring out how to refresh the forms based on updated serviceid values without doing a full page reload.
I can use something like this with jinja2 include to render "form_select.html" and pass the "serviceid" variable so the right form is rendered:
<div id="loadform"> {% include './form_select.html' with serviceid %} </div>
This is working on first load, but I need to select a new form when the user selects a new value from a dropdown. I am running a script based on mydropdown.onchange, which first obtains the correct "serviceid" value, but now I need to rerender just the loadform div with this value.
I have tried approaches along the lines of the following - but I cant seem to figure out how to deliver this jinja2 with .innerHTML.
document.getElementById('loadform').innerHTML = `
{% with serviceid=serviceid %}
{% include './form_blocks.html' %}
{% endwith %}
`;
There is probably a better way to do this, but the examples I can find don't include passing in a variable. Can I use innerHTML for this, or is there a better way?

Related

accessing django form variable in javascript which is inside html page

I have django form with name and email address as a form field in forms.py file.
I am implementing that form in HTML Page with the help of {form.as_p}.
Now I have JavaScript inside that same HTML page with...
{% block javascript %}
<script>
</script>
{% endblock %}
Now How can I access both form variable inside this script tag. I want to validate data at client-side and than wants to send at server.
Will getElementById() method works? and If so what I need to write for access my form variables or any other good alternative.
Thanks
Yes, its possible. Django gives an id in format id_fieldname to each field you define in your Django form.
E.g. For name field, id in HTML will be id_name and For email_address field ,id in HTML will be id_email_address
Now you can simply use getElementById() in your JS with these ID for validation.

django/javascript populating table on the fly

I have a huge database with multiple tables. Essentially I want the table I have to populate on the fly based on what the user clicks from a menu that is populated from the same database. I'm new to django and don't really know how to go about doing this. Right now all the information I need is being passed to the page when it renders and because of that my page is loading extremely slowly. Basically I have a function that is called when something from the menu is clicked that loops through everything I have passed to the page to populate the table accordingly.
To give you a better picture, let's say I have a table of stores and another table of the monthly revenue in my database. The table on the webpage will display the latest 5 data points (ie, the date (month and year), the revenue, and the store name). How do I populate the table based on the selection from the menu?
My menu is populated as follows:
{% for a, storeList in stores.items %}
<div class="overview">
<div><b>{{a}}</b></div>
{% for s in storeList %}
<div id = "{{s.storename}}" onclick="changeSiteInfo(this.id);"{{s.storename}}</div>
{% endfor %}
</div>
{% endfor %}
Thanks for the help =)
You can try integrating DataTables using one of the apps descirbed here.

Django - Update page with ajax data

[Edited for more clarity]
My problem is more of an architecture problem, I have thoughts of many ways to do what I need to but can't figure out which one is correct/the best, so here it is.
I fetch some xml from a remote webserver using ajax, then parse it with jquery.What I want is that when the page is first rendered I have some "loading" gifs, one for each ajax request i'll be making , then when the data is fetched, it appears on the page.
The things is I want to have jquery post these data to the view to render it. ( This is for the other developers who will be using my app, who don't know much of javascript and prefer to write python/html to code the way they want the data to be displayed and make use of the django template engine for custom tags and stuff)
The question is how can I distinguish between the first loading of the page where we have no data and the second time where we have the data. I don't want to have to refresh the page at any time. I thought of having something in the template like :
{% block content %}
{% if not data %}
it's the first loading of the page,we have to fetch the data.
<p> My first item : some loading logo </p>
<script>
call a static script that gets the data then appends it to the html/post it back.
</script>
{% endif %}
{% if data %}
the data had already been fetched so we can display it, something like :
<p> My first item : {{first item}} </p>
{% endif %}
{% endblock %}
I have looked on other questions but it is usually updating with data from the database. Sorry if the question is too specific but I want to really have a good design of the problem before starting to write code and I'm a bit lost. Thank you .
Why do you want to send the parsed data back to the server just for transforming it into Html ?
Why not just use some kind of Javascript based rendering library that can do this ? Your appliation would perform faster since you don't need to execute an extra request.
Django tags and context dict are resolved when template is rendered for the first time.
AJAX is used to post/fetch data withoud page reload, so after AJAX request your page will not be reloaded - and django template renderer will have no possibility to show updated data.
But you could use jQuery get() or post() to retrieve rendered template from other django view and integrate it into current page.
This template must be rendered at request on /ajax/fetch/:
{% block content %}
{% if not data %}
it's the first loading of the page,we have to fetch the data.
<p> My first item : some loading logo </p>
<script>
call a static script that gets the data then appends it to the html/post it back.
</script>
{% else %}
the data had already been fetched so we can display it, something like :
<p> My first item : {{first item}} </p>
{% endif %}
{% endblock %}
And this is sitting on your main page:
<script [include jquery here]></script>
<script>
$(function(){
$("#get_data_please").click(function(){
$.get('/ajax/fetch/', function(data) {
// this is called on ajax success
$('#ajax_result').html(data);
});
});
});
</script>
...
Click to get data
<div id="ajax_result">
Here all will be loaded
</div>

How to send values via ajax from django template to views?

I have a select box that calls a function on changes. The function finds the selected value from "Products" selectbox.
I want to throw that selected value to my views.py which after some operations return the list of data and Populates the Destination's selectbox.
I want to use ajax for this purpose. Please help.
My code looks like this:
<script type="text/javascript">
function select_value()
{
var e = document.getElementById("Product");
var prod = e.options[e.selectedIndex].text
console.log(prod)
}
</script>
This is what my selectbox look like:
<table>
<tr>
<td>
<select id="Product" onChange="select_value();">
{% for products in product_name_list %}
<option>{{products|safe}}</option>
{% endfor %}
</select>
</td>
<td>
<select id="dest">
{% for des in destinations_name_list %}
<option>{{des|safe}}</option>
{% endfor %}
</select>
</td>
</tr>
</table>
This is my views.py:
def selection_filter(request,prod):
destination_objs = Destination.objects.filter(product=prod)
destination_name = destination_objs.values_list('name')
destination_name_list = []
for iter_name in destination_name:
destination_name_list.append(iter_name[0].encode('utf-8'))
return render_to_response('temp/test.html',
{"destination_name_list" : destination_name_list},
)
I think the point you might be misunderstanding is that your Django template for your whole page will not be re-rendered "magically". In Django's standard model-view-template paradigm, the template is rendered just once, upon the initial request. The way you've written it, unless there's a default product selection, you're going to have an awkward empty <select> in the first render. But ignoring that...
For a problem like this, you need two views: one for rendering the whole page, and one for providing the Ajax response. There are two main options for the second view: 1) return JSON for interpretation/rendering by your script post-response or 2) return a fully rendered HTML fragment for direct insertion into your DOM. In this case, I'd just go for option 2.
I recommend looking into Jquery, as it makes Ajax and DOM manipulation super simple.
If you've got Jquery, it's as simple as adding to your script:
$.get('/destinations/' + prod)
.done(function (html) {
$(#dest).html(html);
});
(You can do the same thing without Jquery too, but it requires a bit more wrangling)
Your test.html file should contain:
{% for des in destinations_name_list %}
<option>{{des|safe}}</option>
{% endfor %}

Creating confirmation dialog pages when Javascript is disabled

I'm using Django and I want my users to confirm that they really want something to be deleted. I'm considering pure Django solution (no Javascript confirmations).
According to what I think,I can create a new page containing "Yes" and "No" buttons. If user presses "Yes", my site will go on and delete the object from the database.
Is it the right way to do deletion without using Javascript? How would you implement the feature if you were me?
I would use Django's built in DeleteView, which will display a confirmation page for an HTTP GET request and perform deletion for an HTTP POST request.
The documentation gives this example:
from django.views.generic.edit import DeleteView
from django.core.urlresolvers import reverse_lazy
from myapp.models import Author
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('author-list')
I'd recommend reading the documentation for the SingleObjectMixin which explains how to customise the way the view finds the object to delete (the default is to look for an URL keyword argument called pk), and for the TemplateResponseMixin which explains how to customise the template that is used (the default is 'myapp/author_check_delete.html').
This is just one of a number of class-based generic views that make basic operations (displaying a page for a single model instance, for a list of model instances, and handling editing, deletion etc.) very quick and easy to implement.
If you wanted to enhance this with JavaScript later you could always write some unobtrusive JS that detects links to the deletion confirmation page (by looking for a class, or a particular URL) and adds a click handler that pops up a confirmation dialog and then sends a POST request to the URL in the link's href attribute. You would also need to modify the view slightly to return a JSON object when request.is_ajax() is True, so that your JS would know if the deletion had succeeded or failed, which would probably involve overriding one of the methods inherited from the DeletionMixin.
That sounds fine. What I have done a couple of times is to create a confirmation template that can be used anywhere in the application:
{% extends 'base.html' %}
{% block content %}
<div class="confirmation-box">
<p>{{ message }}</p>
<div>
Cancel
<form action="{{ action_link }}" method="post">
<input type="hidden" name="next" value="{{ prev_link }}" />
<input type="submit" value="Send" />
</form>
</div>
</div>
{% endblock %}
You pass to it:
A confirmation message for the user (message)
The url to the page you are in (prev_link)
The url that should be called to perform the action (action_link)
If the user cancels the action, then she/he goes back to the original page.
If the user confirms, then the prev_link is passed as a hidden parameter, so the view can redirect the user to the original page after performing the action (although this is completely optional of course).
Which is pretty much what you propossed in your question.

Categories