jQuery datetimepicker- unable to select date from next year - javascript

I am working on a Python/ Django project, and one of the forms on a webpage has a datetimepicker field on which the user can select a date/ time from the drop-down that appears when the field is selected.
The problem that I currently have is that although the calendar displays a full month at a time, and the user can move through months/ years at a time by selecting next/ previous month, or choosing the year from a drop down inside the calendar, if they move to a month beyond the end of this year, then none of the dates are available for selection.
Having Google'd datetimepicker, it seems that this is a jQuery function, and I want to make sure that there is no value for its maxDate attribute- I've looked through jquery.datetimepicker.full.js, and although it's referenced there, it doesn't see to be given a value at all... so I can't see why this field is not allowing me to select a date beyond the end of this year... anyone have any ideas?
The view that is rendering this page is:
def concept(request, project_id):
project = Project.objects.prefetch_related('budget_versions').get(id=project_id)
deposit = Deposit.objects.get_or_create(project=project)[0]
presentations = project.budget_versions.select_related('meeting').prefetch_related('budget_items', 'cci_items', 'presenters').filter(version_number__isnull=False).annotate(vn=F('version_number') * -1).order_by('presentation_date', 'created', '-vn')
end_details = EndDetails.objects.get_or_create(project=project)[0]
presentation_formset = BudgetPresentationFormset(prefix="presentations", instance=project, queryset=presentations)
drawing_formset = DrawingUploadFormset(prefix="drawings", queryset=Drawing.objects.filter(budget__in=presentations).order_by('budget__presentation_date', 'budget__created'))
context = {
'project': project,
'presentations': presentations,
'presentation_formset': presentation_formset,
'drawing_formset': drawing_formset,
'deposit_form': DepositInfoForm(instance=deposit),
'ended_form': EndDetailsForm(instance=end_details),
'budget_notes_form': BudgetNotesForm(instance=project.budget_overview),
}
return render(request, 'projects/concept.html', context)
and the Django that is displaying the form on which the 'date' field is displayed is:
{% if not forloop.last and presentation_form.instance.budget_items.count %}
<tr class="split-rows">
<td colspan="3">Exc VAT {% if not presentation_form.instance.current_marker %}{{presentation_form.instance.grand_total_exc_vat|money:'£'}}{% else %}{{project.budget_overview.updated_exc_vat|money:'£'}}{% endif %}</td>
<td colspan="3">Inc VAT {% if not presentation_form.instance.current_marker %}{{presentation_form.instance.grand_total_inc_vat|money:'£'}}{% else %}{{project.budget_overview.updated_inc_vat|money:'£'}}{% endif %}</td>
</tr>
{% endif %}
<tr>
{% for hidden in presentation_form.hidden_fields %}
<td class="hidden">{{ hidden }}</td>
{% endfor %}
</tr>
{% for field in presentation_form.visible_fields %}
<tr class="split-rows">
{% if not field.name == 'pdf_package_dep' %}
<td colspan="6"><label>{{field.label}}</label></td>
{% endif %}
</tr>
<tr class="split-rows">
<td colspan="6">
{% if not field.name == 'pdf_package_dep' %}
{% if field.name == 'presentation_date' %}
{% with presentation_form.instance.meeting as meeting %}
{% include "projects/includes/meeting_bit.html" with employee=request.user.employee meeting=meeting UID=presentation_form.instance.id %}
{% endwith %}
{# <a class="ical_trigger button" data-view-url="{% url 'events:add_to_cal' %}" {% if not field.value %}style="display:none"{% endif %}>Add to calendar</a> #}
{% else %}
{{field}}
{% endif %}
{% endif %}
</td>
</tr>
{% endfor %}
Edit
It would appear that what's actually displaying the calendar is the HTML file included by the line:
{% include "projects/includes/meeting_bit.html" with employee=request.user.employee meeting=meeting UID=presentation_form.instance.id %}
The meeting_bit.html file has the following code:
{% if meeting and meeting.event_creator and meeting.event_creator != employee %}
<table>
<tr>
<td>
{{meeting.date|date:"d/m/Y H:i"}}<br>
</td>
<td rowspan="2"><a class="change_event_organiser" data-view-url="{% url 'events:change_event_creator' meeting.id %}" class="button">Edit</a></td>
</tr>
<tr>
<td class="text-sm">
Organised by {{meeting.event_creator}}
</td>
</tr>
</table>
{% else %}
<div id="cal_{{field.name}}_{{UID}}">
{{field}}
<a class="ical_trigger button" data-view-url="{% url 'events:add_to_cal' %}" {% if not field.value %}style="display:none"{% endif %}>
{% if meeting.event_id %}Update calendar event{% else %}Add to calendar{% endif %}
</a>
</div>
{% endif %}
I can see when I 'inspect' the date field of the form in the browser, that it is in a div which has an ID in the format cal_{{field.name}}_{{UID}}, so I know that this is where the calendar is initialised/ displayed... But I can't see anything that is restricting the available options for selection to dates from this year only... why can't I select a date from next year, or any other year in the future?

Related

Javascript does not work in the second page of a data table

Actually I'm working with the following datatable:
Data Table code:
<table aria-describedby="dataTable_info" cellspacing="0" class="table table-hover dataTable" id="dataTable" role="grid" style="width:100%;" width="100%">
<thead>
<tr>
<th>{{'fsaGeneralPlan.table.Auditors'|trans({}, 'FSABundle')}}</th>
<th>{{'fsaGeneralPlan.table.Audits'|trans({}, 'FSABundle')}}</th>
<th>{{'fsaGeneralPlan.table.Areas'|trans({}, 'FSABundle')}}</th>
</tr>
</thead>
<tbody>
{% for audit in auditsByArea %}
{% set myArray = audit.Audits|split(',') %}
{% set AuditsStatus = audit.AuditsStatus|split(',') %}
<tr>
<td>{{ audit.Auditor }}</td>
<td>
{# {% set long = numberOfAudits|length + 2 %} #}
{# <h1>{{ long }}</h1> #}
{% for i in 0..3 %}
{% set e = i + 1 %}
<a title="{{ AuditsStatus[i] }}" class="btn btn-outline-primary btn-sm auditButton {{ AuditsStatus[i] }}" data-id="Audit{{ myArray[i] }}" data-area="{{ audit.area_name }}" data-status="{{ AuditsStatus[i] }}" id="auditButton{{ myArray[i] }}" name="auditButton">{{'w' ~ e }}</a>
{# <input class ="auditButton {{ AuditsStatus[i] }} mx-2" value="{{'W' ~ i }}" href="" data-id="Audit{{ myArray[i] }}" data-area="{{ audit.area_name }}" data-status="{{ AuditsStatus[i] }}" id="auditButton{{ myArray[i] }}" name="auditButton" type='text' readonly ></input> #}
{% endfor %}
</td>
<td>{{ audit.area_name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
And I have this Javascript to change the class of the buttons in the datatable once that the page is loaded:
<script type="text/javascript">
$(document).ready(function(){
$(".auditButton.Submitted").removeClass('btn-outline-primary');
$(".auditButton.Submitted").addClass('btn-outline-success');
$(".auditButton.Expired").addClass('btn-outline-danger');
$(".auditButton.Capturable").addClass('btn-outline-warning');
});
It works correctly but just in the first page of the datatable, it does not work in the other pages.
Any idea or subject of how to fix it or what is wrong?
You need to listen to the draw event for your table.
Why?
Your current setup works fine for the first page, because those elements are all rendered when $(document).ready() fires. However, the other pages are rendered after the document is ready.
Try:
const table = $('#dataTable').DataTable();
// Event listener for DT 1.10+
table.on('draw', function() {
$(".auditButton.Submitted").removeClass('btn-outline-primary');
$(".auditButton.Submitted").addClass('btn-outline-success');
$(".auditButton.Expired").addClass('btn-outline-danger');
$(".auditButton.Capturable").addClass('btn-outline-warning');
});
Doing this, you can also remove the same block of code from `$(document).
You can also place all this inside the draw callback for your datatable if you'd prefer:
const table = $('#dataTable').DataTable({
drawCallback: function(settings) {
// changes in here
}
});

Django referencing Javascript variable in server side template code

I have a page that adds textboxes dynamically, and on the dynamically added text boxes, I want to access the relevant context variable.
To do so, I somehow need to use the 'i' variable inside the javascript code/template code to reference it's value in the context.
Here's my javascript code where I need to use 'i' as an index for a context list:
<script>
var i = 2
function add_field()
{
var table = document.getElementById("tbl_location").getElementsByTagName('tbody')[0];
var input_name = document.createElement("th")
input_name.appendChild(document.createTextNode("S/N " + i))
var input_tb = document.createElement("td")
var input = document.createElement('input');
input.setAttribute("name", "sn" + i);
{% if curr_sn.i %}
input.setAttribute("value", {{ curr_sn.i }});
{% endif %}
input_tb.appendChild(input)
var input_row = document.createElement("tr")
input_row.appendChild(input_name)
input_row.appendChild(input_tb)
table.appendChild(input_row);
i++;
}
The specific lines are:
{% if curr_sn.i %}
input.setAttribute("value", {{ curr_sn.i }});
{% endif %}
Where 'i' is a javascript veriable, and curr_sn is a list the python code gives as a context.
The html part where I need to use 'i':
{% for i in max_board_list %}
{% if curr_sn.i %}
<tr>
<th>S/N {{ i }}</th>
<td><input type="text" name="sn{{ i }}" value="{{ curr_sn.i }}"></td>
</tr>
{% endif %}
{% endfor %}
Here 'i' is generated by a for loop, but I still need to access the same list.
How can I do this in both parts of code? All I could find the the opposite way which already works for me (using django template in javascript code).
Thanks
EDIT: for javascript side i found a solution (since I noticed that anyway my code is redundant and tries to do similar things in js&html). For the javascript part I use:
{% if curr_sn|length > 1 %}
i = {{ curr_sn|length }}
{% endif %}
Just to keep counting from the current number of boards.
Now I need to solve the html parts to display the saved boards in the context variable curr_sn
Found a solution for the html part as well.
I just use custom filters to do the checking.
I've registered two filters:
#register.filter(name='is_in')
def is_in(index, list):
if list is None:
return False
try:
list[int(index)]
return True
except:
return False
#register.filter(name='get_value')
def get_value(index, list):
if list is None:
return False
try:
return list[int(index)]
except:
return None
And in the HTML part I use the following:
{% for i in max_board_list %}
{% if i|is_in:curr_sn %}
<tr>
<th>S/N {{ i }}</th>
<td><input type="text" name="sn{{ i }}" value="{{ i|get_value:curr_sn }}"></td>
</tr>
{% endif %}
{% endfor %}
Hope this will help for others with the same problem.

Pass an array of a twig for a jQuery

I have a block on my twig writing a table from a variable received from controller
{% block foot_informations %}
{% if ads is not empty %}
<div class="panel-foot-information row">
<table id="ads">
<thead>
<tr>
<th>Departure</th>
<th>Destination</th>
</tr>
</thead>
<tbody>
{% for ad in ads %}
<tr class="ad-tr">
<td>{{ ad.departure }}</td>
<td>{{ ad.packageType }}</td>
<td>{{ ad.transportation }}</td>
{# <td>{{ ad.date }}</td> #}
<td>select</td>
<td class="hidden"><input type="hidden" id="idLat" value="{{ ad.departureLatitude }}"/></td>
<td class="hidden"><input type="hidden" id="idLong" value="{{ ad.departureLongitude }}"/></td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endif %}
{% endblock %}
I would like to get this variable month in JQuery to manipulation it and then rewrite my table
to catch it saw something like this: var ads = {{ ads|json_encode() }};
My idea is in a evnto of button to click to change the value of the array and reconstruct the table someone help me?
$('#my_button').click(function () {
alert(ads);
$.each(ads, function(){
alert($(this));
//filter by type package
});
//rewrite table
});
First of all I would suggest that you don't mix two strategies.
is generating views serverside, what you obviously do with the twig templates.
is passing raw data (with AJAX or like your example with the json_encoded array parsed into a JS Object), and then generating the table with JS DOM manipulation.
But that's my opinion about this part.
If you choose for Option 1 you could add/remove classes in your $.each filter-like callback for the table rows you want to hide / show.
And then write something like this in your stylesheet
tr.filtered {
display: none;
}
Alternative: extend your table body like this:
<tbody>
{% for ad in ads %}
<tr data-ad-id="{{ ad.id }}" class="ad-tr">
<td>{{ ad.departure }}</td>
{# all the other td's #}
</tr>
{% endfor %}
</tbody>
And you Clickhandler:
$('#my_button').click(function() {
//alert(ads);
$.each(ads, function(index, ad) {
if (ad.packageType == 'some_package_type') {
$('table#ads tr[data-ad-id=' + ad.id + ']').hide();
}
});
// rewrite table
// Perhaps there is no need for anymore
});
EDIT:
If you have a javascripts block in your base template, you could do this to expose an ads array to the global JS scope (just like you said in the question, about what you have seen):
{% block javascripts %}
{{ parent() }}
<script>
var ads = {{ ads|json_encode() }};
</script>
{% endblock %}

Jquery datatable First load as html then paginate through ajax

I am working on an already written code base. I have to implement ajax pagination to a table. Right now we are using jquery datatable. When the page is opened they content is loaded as html thought jinja templating.
<table id="dataGrid" class="display">
<thead>
<tr>
{% if app_ctx.sub_nav == 'mine' or app_ctx.category == 'members' %}
<th class="no_sort mid"><input type="checkbox" value="" name="" id="dataGrid_check_all" /></th>
{% endif %}
{% if app_ctx.root == 'lab' %}
<th></th>
{% endif %}
<th>Access</th>
{% for field_title in field_titles() %}
<th>{{field_title}}</th>
{% endfor %}
</tr>
</thead>
<tfoot>
<tr>
{% if app_ctx.sub_nav == 'mine' or app_ctx.category == 'members' %}
<th></th>
{% endif %}
{% if app_ctx.root == 'lab' %}
<th></th>
{% endif %}
<th>Access</th>
{% for field_title in field_titles() %}
<th>{{field_title}}</th>
{% endfor %}
</tr>
</tfoot>
<tbody>
{% for item in items %}
<tr>
{% if app_ctx.sub_nav == 'mine' or app_ctx.category == 'members' %}
<td><input type="checkbox" class="item-ids" value="{{ item.id }}" /></td>
{% endif %}
{% if app_ctx.root == 'lab' %}
<td><a target="_blank" href="{{ '%s/%s' % ( app_ctx.url_for('details'), item.id) }}">More...</a></td>
{% endif %}
<td>{% if app_ctx.sub_nav != 'mine' %}<input name="item_ids" type=hidden value="{{ item.id }}">{% endif %}
<div style="width: 65px; display: block; overflow: auto;">{{ acl_display(item) }}</div></td>
{% for field_value in field_values(app_ctx, item) %}
{{field_value|safe}}
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
What i need to do is, I just want to load first ten records as html and then load rest of the pages through Ajax request. Please tell how can this be achieved.
current js code
var table = $("{{ selector }}");
var dataTableInitOptions = {
"sPaginationType": "full_numbers",
"bJQueryUI": true,
"aaSorting": {% if app_ctx and app_ctx.category == 'files' and app_ctx.sub_nav == 'mine' %}[[ 7, "desc" ]]{% else %}[[ 1, "desc" ]]{% endif %},
"oLanguage":{
"sSearch":"Search all columns:"
},
"bStateSave": true {# save search and sorting state in cookies #}
};
{% if init_options %}
var additionalOptions = ({{ init_options|safe }});
for (var i in additionalOptions) {
dataTableInitOptions[i] = additionalOptions[i];
}
{% endif %}
if (table.width() > 900) {
dataTableInitOptions.sScrollX = 920;
dataTableInitOptions.bScrollCollapse = true;
//dataTableInitOptions.sScrollXInner = table.width();
}
dataTableInitOptions.fnInitComplete = function() {
{% if filters and filters_placed_in_table %}{{ filters.render_filters_js() }}{% endif %}
{# sort by Uploaded #}
{% if app_ctx and app_ctx.category == 'files' %}
{% if app_ctx.sub_nav == 'mine' %}
this.fnSort( [[7,'desc']] );
{% else %}
this.fnSort( [[6,'desc']] );
{% endif %}
{% endif %}
//move footer column filters to the top
if ($('.dataTables_scroll').length) {
var scrollParts = $('.dataTables_scroll').children();
var footer = scrollParts[2],
body = scrollParts[1];
scrollParts[1] = footer;
scrollParts[2] = body;
$('.dataTables_scroll').append(scrollParts);
} else {
//no scroll
//append empty row to the header and move footer in place of that row
$(this).css({position:'relative'});
var footer = $('tfoot tr', $(this)).children(),
colNum = footer.length,
header = $('thead tr:first', $(this)).children();
var widths = header.map(function(){return $(this).width()});
$('tfoot', $(this)).css({'position':'absolute', 'top': $('thead', $(this)).height() + 'px', 'left':'0', 'right':'0'});
$('thead', $(this)).append($('<tr></tr>').css({'height':$('tfoot', $(this)).height() + 12 + 'px'}));
footer.each(function(i, el) { $(el).width(widths[i] + 2) });
}
};
$("{{ selector }}").dataTable(dataTableInitOptions).columnFilter();

How do I code a count for double nested for loop?

I'm trying to pass just the piece number to my html. This will be used to update the content of a selected tag with javascript. All of my tags are created by a double nested for loop in django. But from what I've tried I've had no success.
Here is the javascript code:
$('td#'+new_data['piece_number']).html(new_data['img']);
Here is the double nested for loop in question:
<table id="table" bgcolor="{{puzzle.color_hash}}">
<tbody>
{% for x in n_rows %}
<tr id='r{{x}}'>
{% for y in n_cols %}
<td id='{{count}}' height='{{puzzle.piece_res_height}}' width='{{puzzle.piece_res_width}}'>
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
I want the total iteration count in {{count}} but from my understanding django doesn't let you have variable manipulation in the renderer
I'm looking for a result such as a row by column table...
1 2 3
4 5 6
7 8 9
Where there are 3 rows and 3 columns. 9 pieces. each with a td id of the piece number
i.e. row 2 column 2 has a td id of 5
You can send two wariables instead one count to html file and change ida of id naming.
<td id='r{{x}}d{{y}}' height='{{puzzle.piece_res_height}}' width='{{puzzle.piece_res_width}}'>
Edit - right solution
Ok, I have two solutions for you.
Both use custom template filters.
File app/templatetags/default_filters.py
from django import template
register = template.Library()
#first way
def mod(value, arg):
return value % arg == 0
#second way
#register.filter(name='multiply')
def multiply(value, arg):
return value*arg
register.filter('mod', mod)
Context send to template
class MainSiteView(TemplateView):
template_name = "main_page.html"
def get_context_data(self, **kwargs):
context = super(MainSiteView, self).get_context_data(**kwargs)
n_rows = n_cols = 2
context['max_nums'] = n_rows * n_cols
context['n_rows'] = [0, 1]
context['n_cols'] = [0, 1]
context['number_of_columns'] = 2
context['range'] = [x for x in range(n_cols * n_rows)]
return context
And template
{% load default_filters %}
<table id="_table" bgcolor="{{puzzle.color_hash}}">
<tbody>
{% for x in range %}
{% if not forloop.counter|mod:number_of_columns %}
<tr id='_r{{x}}'>
{% endif %}
<td id='_{{forloop.counter0}}' height='{{puzzle.piece_res_height}}' width='{{puzzle.piece_res_width}}'>
({{forloop.counter0}})
</td>
{% if forloop.counter|mod:number_of_columns %}
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>
<table id="table" bgcolor="{{puzzle.color_hash}}">
<tbody>
{% for x in n_rows %}
<tr id='r{{x}}'>
{% for y in n_cols %}
<td id='{{x|multiply:number_of_columns|add:y}}' height='{{puzzle.piece_res_height}}' width='{{puzzle.piece_res_width}}'>
[{{x|multiply:number_of_columns|add:y}}]
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>

Categories

Resources