django/javascript populating table on the fly - javascript

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.

Related

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

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?

Django forms for quiz app ( how to disable a form after submission )

I am creating a classroom app. Which has a exam section where students can give test. If a student wants to give a exam he/she has to select subject and then has to go in exam section. I want student to have access to exam form for one time.
One possibility to do this is as follows. Note that there are many more options available to you, which one is the easiest depends on your entire application.
Keep track of your students' exam results:
class ExamResult(Model):
student = ForeignKey(User, related_name='exam_results')
exam = ForeignKey(Exam, related_name='exam_results')
...
In your form template, check whether the student has already an ExamResult object associated with the exam. You could do this in two parts:
In your context builder, define a variable with all the new exams.
exams_taken = ExamResult.objects.filter(student=user).values_list('exam_id', flat=True)
new_exams = Exam.objects.exclude(id__in=exams_taken)
In your form, loop over the new_exams only.
{% for exam in new_exams %}
{# show the form for this exam #}
{% endfor %}

How to associate dynamic value with HTML elements?

I want to create a list which is clickable and which would allow me to take a survey when I click it.
{% extends "layout.html" %}
{% block title %}
Take Survey
{% endblock %}
{% block main %}
<div class="list-group">
{ for search in searches }
{{search.topic}}
{ endfor }
</div>
{% endblock %}
When I click it I want it to go to a page which shows the questions of the survey whose topic was being shown.
I have created SQL tables for users,surveys,questions and options. Surveys are linked to users, questions are linked to surveys and options are linked to questions.
I just need a way to access the survey id({{search.id}}) in my take route where I could run a SQL query using the survey id to link everything.
Just a disclaimer, I am a beginner in HTML so please try to explain elaborately.
There are multiple ways that you can do this with html, here are a few of them
create a hidden input with the value that u need, and later when u need it retrieve it from that input
<input type="hidden" id="searchId" name="searchId" value="3487">
add a custom attribute to an element, and later when needed retrieve it from that element
<div class="list-group">
{ for search in searches }
{{search.topic}} data-search-id="{{search.id}}"
{ endfor }
</div>
There are also multiple ways you can do this without html
insert a script that has the search id, and later retrieve that id from javascript
{% block main %}
<div class="list-group">
{ for search in searches }
{{search.topic}}
{ endfor }
<script>
// just make sure that this variable is unique, so u dont cause errors or overwrite another variable by mistake
const MY_APP_SEARCH_ID ={{search.id}}
</script>
</div>
{% endblock %}
You could also generate a unique url for each survey
{{search.topic}}
and then handle that search id from the \take endpoint

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 dynamically access objects in a twig template with symfony2

I don't even know what title use to this question. I'm starting with web programming and I don't even know what technology should I use to do this.
I have a database with doctrine in symfony2. This database has galleries and each gallery has images (two tables OneToMany relation).
I'm passing an array of galleries to a twig template where I show them in a select, so I can choose one and add more images to the gallery, add new galleries or delete them using the submit buttons.
That is working now with this template:
<select class="listGalleries" id="listGalleries" name='id' size="10">
{% for gallery in galleries %}
<option value="{{gallery.id}}" >{{gallery.name}}</option>
{% endfor %}
</select>
That goes inside the form.
Now, what I want to do is everytime I do click in one item of the select, show, in the same webpage, all the images of the gallery selected.
I don't know which technology should I use. Can I do it with twig? Do I have to learn ajax? I guess I have to go to the database to read the data of the pictures that belongs to that gallery, but I don't know how to do it or if symfony2 offers me a better solution.
Every advice will be appreciated.
"Dynamically" can't be done in twig, since after its rendering there is no way to change the output.
You can do in two ways in my opinion:
Use twig to loop within galleries and output them, then use some javascript like bootstrap tabs to display each gallery when changing option. in bootstrap you would do this way (assuming the gallery->images relations is in $gallery->images):
<div class="tab-content">
{% for gallery in galleries %}
<div class="tab-pane active" id="gallery{{ gallery.id }}">
{% for image in gallery.images %}
<img src="{{ image.url }}" class="img-polaroid">
{% endfor %}
</div>
{% endfor %}
</div>
now using javascript like
$("select#listGalleries").change(function () {
$("select option:selected").each(function () {
$("#gallery" + $(this).attr('value')).tab('show');
});
})
Otherwise you can use ajax to return the gallery images after having selected a gallery from the and render the gallery images somewhere on the page. This could be done in two ways, render the html within symfony and just place the output in the page with javascript or return just a json (using something like this) and create the html within javascript (I personally use a lot pure).

Categories