How to change variable inside twig in javascript - javascript

I want to change the variable inside Twig by javascript, but there is an error: Variable "max" does not exist.
my twig:
{% block body %}
<label for="maxN">Niveau MAX</label>
<input type="number" id="maxN" class="form-control">
{{ form_label(form.ncUoCommandeUo) }}
{{ form_widget(form.ncUoCommandeUo, {'attr':{'min':1, 'max': max}}) }}
{% endblock %}
{% block javascripts %}
<script>
my.ajax......
if (ncMaxUo.val() === 1) {
max = 1;
} elseif(ncMaxUo.val() === 2) {
max = 2;
} elseif(ncMaxUo.val() === 3) {
max = 3;
} else {
max = 4;
}
....
</script>
{% endblock %}

Just update my solution.
{% block body %}
<label for="maxN">Niveau MAX</label>
<input type="number" id="maxN" class="form-control">
{{ form_label(form.commande) }}
{{ form_widget(form.commande, {'attr':{'min':1}}) }}
{% endblock %}
{% block javascripts %}
<script>
my.ajax......
var maxN = $("#maxN");
maxN = ???;(get value from ajax)
$("#commande").attr("max", maxN.val());
....
</script>
{% endblock %}

Related

Django/ Javascript : Custom the visual of adropdown menu a form.ChoiceFiled

I have an app with a form that is split in several steps with FormWizard.Some fields are multichoice fields with thousands of choices. I want to improve the presentation of the dropdown menu. I would like to replace it by a kind of fixed list with a scrollbar, like that few data is always displayed and the user sees it wihout clicking on the dropdown to show it.
However I do not know how to do that, if it is with Javascript or CSS. I create the form wiht django and I call it.
Anyone can help me or show me an example ?
forms.py
class ClientForm1(forms.Form):
client = forms.ChoiceField(label="Client :")
def __init__(self, uuid_contrat, *args, **kwargs) :
super(ClientForm1, self).__init__(*args, **kwargs)
id_contrat = Entity.objects.all().filter(uuid=uuid_contrat).values_list('id', flat=True)[0]
client_choices = Toriiclients.objects.filter(idcustomer=id_contrat).order_by('-id').values_list('id', 'prenom')
self.fields['client'].choices = client_choices
class SaletypeForm2(forms.Form):
saletype = forms.ChoiceField(label="Client :")
information =forms.CharField(max_length=1000)
def __init__(self, uuid_contrat, *args, **kwargs) :
super(SaletypeForm2, self).__init__(*args, **kwargs)
id_contrat = Entity.objects.all().filter(uuid=uuid_contrat).values_list('id', flat=True)[0]
client_choices = ToriiLstAffairetype.objects.filter(idcustomer=id_contrat).order_by('-id').values_list('short_desc', 'short_desc')
self.fields['saletype'].choices = client_choices
views.py
from django.shortcuts import render
from .forms import ClientForm1, SaletypeForm2
from formtools.wizard.views import SessionWizardView
class FormWizardView(SessionWizardView):
template_name = "sales/formwiz.html"
form_list = [ClientForm1, SaletypeForm2]
def get_context_data(self, form, **kwargs):
context = super(FormWizardView, self).get_context_data(form, **kwargs)
uuid_contrat = self.kwargs['uuid_contrat']
id_contrat = Entity.objects.all().filter(uuid=uuid_contrat).values_list('id', flat=True)[0]
context['last_clients_created'] = Toriiclients.objects.filter(idcustomer=id_contrat).order_by('-id')[:10]
return context
def done(self, form_list, **kwargs):
return render(self.request, 'done.html', {
'form_data': [form.cleaned_data for form in form_list],
})
def get_form_kwargs(self, step,) :
uuid_contrat = self.kwargs['uuid_contrat']
kwargs = super(FormWizardView, self).get_form_kwargs(step)
kwargs["uuid_contrat"] = uuid_contrat
return kwargs
html
{% extends "layout.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
{% if wizard.steps.step1 == 1 %}
{% endif %}
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
<input type="submit" value="{% trans "submit" %}"/>
</form>

How do I break up and display only 1 of three variants at a time?

I'm looking to build a multi-step product selector using tabs. I'm looking to display on variant per tab but can't find a way to break up variants to display them individually.
I have tried posting the code bellow multiple times (one in each tab) but this makes each selection "stuck". Yes I know this would of led to issues but I was just trying to make the code work.
<div class="product-size option-{{ option | handle }} {{ product_options }}">
<span class="option-label">{{ option }}:</span>
<div class="select-wrapper-sm">
<select class="form-control input-sm size-variants">
{% for name in option_names %}
<option {% if selected_value == name %}selected="selected"{% endif %} value="{{ name | handle | downcase | escape }}">{{ name }}</option>
{% endfor %}
</select>
</div>
{% if product_options == 'swatches' %}
<ul class="{% if option_title contains 'color' %}color-list{% else %}size-list{% endif %}" data-index="{{ forloop.index0 }}">
{% for name in color_image %}
{%- assign title = name | split:':' | first | replace:'!__!','' -%}
{%- assign img_src = name | split:':' | last -%}
<li {% if selected_value == title %}class="active"{% endif %}>
{% if option_title contains 'color' %}<span class="value"><img src="{% if settings.product_previews_colors_variants %}{{ img_src }}{% else %}{{ title | handle | prepend:'color-' | append: '.png' | file_url | downcase }}{% endif %}" alt=""></span>{% else %}{{ title | escape }}</span>{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
Currently the whole product form is being displayed with this code
<div class="product-actions product-id-{{ product.selected_or_first_available_variant.id }} {% if product.variants.size == 1 and quick_view == 'yes' %}product-no-options no-border{% endif %}">
{% form 'product', product %}
{% if product.selected_or_first_available_variant.inventory_management == "shopify" and product.selected_or_first_available_variant.inventory_quantity < 1 and product.selected_or_first_available_variant.inventory_policy == "continue" %}
<input type="hidden" name="properties[{{ 'general.theme.status' | t }}]" value="{{ 'general.theme.pre_order' | t }}">
{% endif %}
{% if product.metafields.c_f.line_properties != blank %}
{{ product.metafields.c_f.line_properties }}
{% endif %}
{% include 'product-options-form' design:'default' %}
{% if product.available %}
<div class="product-actions-row">
<div class="pull-left">
<div class="product-qty">
<div class="qty qty-changer">
<fieldset>
<input type="text" class="qty-input" name="quantity" value="1" data-min="1" {% if product.selected_or_first_available_variant.inventory_management == "shopify" and product.selected_or_first_available_variant.inventory_quantity > 0 and product.selected_or_first_available_variant.inventory_policy == 'deny' %}data-max="{{ product.selected_or_first_available_variant.inventory_quantity }}"{% endif %}>
<input type="button" value="+" class="increase">
<input type="button" value="-" class="decrease">
</fieldset>
</div>
</div>
<div class="product-stock-dynamic {% unless product.selected_or_first_available_variant.inventory_management == "shopify" and product.selected_or_first_available_variant.inventory_quantity > 0 and product.selected_or_first_available_variant.inventory_policy == 'deny' %}hidden{% endunless %} stock-dynamic">{% if product_inventory_count %}max <b>{% if product.selected_or_first_available_variant.inventory_management == "shopify" and product.selected_or_first_available_variant.inventory_quantity > 0 %}{{ product.selected_or_first_available_variant.inventory_quantity }}{% endif %}</b> {{ 'general.theme.itemss' | t }}{% endif %}</div>
</div>
<div class="pull-right">
{% capture status %}{{ 'general.theme.add_to_cart' | t }}{% endcapture %}
{% if product.selected_or_first_available_variant.inventory_management == "shopify" and product.selected_or_first_available_variant.inventory_quantity < 1 and product.selected_or_first_available_variant.inventory_policy == "continue" %}
{% capture status %}{{ 'general.theme.pre_order' | t }}{% endcapture %}
{% endif %}
<div class="product-actions-btn">
<button class="btn btn-lg js-add-to-cart-product-page" data-product-handle="{{ product.handle }}" data-variant-id="{{ product.selected_or_first_available_variant.id }}" title="{{ status }}"><span>{{ status }}</span></button>
</div>
</div>
<div class="product-actions-link">
{% if quick_view == 'yes' %}{% assign position = 'bot' %}{% else %}{% assign position = 'right' %}{% endif %}
{% include 'product-card-and-page-actions' position:position %}
</div>
</div>
{% if section.settings.dynamic_checkout_button %}
<style>
.shopify-payment-button__more-options {
display: none;
}
.shopify-payment-button__button {
outline: none;
border-radius: 0;
text-transform: uppercase;
background: #d3fbc9;
color: #FFFFFF;
padding: 9px 35px 11px;
font-weight: 500;
line-height: 32px;
border: 0;
color: black;
font-weight: bold;
}
.shopify-payment-button__button--unbranded:hover:not([disabled]){
background: black !important;
color: #FFFFFF !important;
}
</style>
{{ form | payment_button }}
{% if section.settings.safe_checkout_image_yes %}
<br />
<h4>{{ settings.checkout_popup_guaranteed_caption }}</h4>
<img src="{% if section.settings.safe_checkout_image != blank %}{{ section.settings.safe_checkout_image | img_url:'master' }}{% else %}{{ 'guaranteed.png' | asset_url }}{% endif %}" alt="" class="img-responsive">
{% endif %}
{% endif %}
{% endif %}
{% endform %}
</div>
which uses {% include 'product-options-form' design:'default' %} to display the following code
<div class="product-options id_{{ product.id }} {{ product_options }} {% if product.variants.size == 1 %}product-no-options no-border{% endif %}">
<input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}">
{% unless product.options.size == 1 and product.options.first == 'Title' %}
{%- assign index = 0 -%}
{% for option in product.options %}
{%- assign option_names = '' -%}
{%- assign option_title = option | downcase -%}
{%- assign index = forloop.index0 -%}
{%- assign selected_value = '' -%}
{%- assign color_images = '' -%}
{%- assign color_image = '' -%}
{% for variant in product.variants %}
{% if variant == product.selected_or_first_available_variant %}
{% assign selected_value = variant.options[index] %}
{% endif %}
{%- assign img_url = variant.image.src | img_url: '1024x1024' -%}
{%- assign option_names = option_names | append:variant.options[index] | append:'<>' -%}
{%- assign color_images = color_images | append : img_url | append:'<>' -%}
{%- assign check_color_name = '!__!' | append:variant.options[index] | append:'!__!' -%}
{% unless color_image contains check_color_name %}
{%- assign color_image = color_image | append:'!__!' | append:variant.options[index] | append:'!__!:' | append:img_url | append:'<>' -%}
{% endunless %}
{% endfor %}
{%- assign color_images = color_images | split:'<>' | uniq -%}
{%- assign option_names = option_names | split:'<>' | uniq -%}
{%- assign color_image = color_image | split:'<>' | uniq -%}
<div class="product-size option-{{ option | handle }} {{ product_options }}">
<span class="option-label">{{ option }}:</span>
<div class="select-wrapper-sm">
<select class="form-control input-sm size-variants">
{% for name in option_names %}
<option {% if selected_value == name %}selected="selected"{% endif %} value="{{ name | handle | downcase | escape }}">{{ name }}</option>
{% endfor %}
</select>
</div>
{% if product_options == 'swatches' %}
<ul class="{% if option_title contains 'color' %}color-list{% else %}size-list{% endif %}" data-index="{{ forloop.index0 }}">
{% for name in color_image %}
{%- assign title = name | split:':' | first | replace:'!__!','' -%}
{%- assign img_src = name | split:':' | last -%}
<li {% if selected_value == title %}class="active"{% endif %}>
{% if option_title contains 'color' %}<span class="value"><img src="{% if settings.product_previews_colors_variants %}{{ img_src }}{% else %}{{ title | handle | prepend:'color-' | append: '.png' | file_url | downcase }}{% endif %}" alt=""></span>{% else %}{{ title | escape }}</span>{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
{% endfor %}
{% endunless %}
<script>
var product_options_{{ product.id }} = [];
{%- assign options = product.options -%}
{% for option in options %}
{%- assign option_index = forloop.index0 -%}
{% for variant in product.variants %}
{%- assign params = variant.options -%}
product_options_{{ product.id }}{% for name in params %}{% if forloop.index0 > option_index %}{% continue %}{% endif %}['{{ params[forloop.index0]|handle|strip|downcase}}']{% endfor %}=[];
{% endfor %}
{% endfor %}
{% for variant in product.variants %}
{%- assign attributes = 'price,compare_at_price,id,image,inventory_quantity,inventory_management,inventory_policy,sku' | split:',' -%}
{% for attribute in attributes %}
product_options_{{ product.id }}{% for option in variant.options %}['{{ variant.options[forloop.index0] |handle|strip|downcase }}']{% endfor %}['{{ attribute|downcase }}']='{% if attribute == 'image'%}{% unless variant.image.src contains 'products' %}{{ product.featured_image | img_url: '1024x1024' }}{% else %}{{ variant.image.src | img_url: '1024x1024' }}{% endunless %}{% else %}{{ variant[attribute] }}{% endif %}';
{% endfor %}
{% endfor %}
</script>
{% if design == 'creative' %}</div>{% endif %}
{% if design == 'default' %}</div>{% endif %}
<script>
{% assign product_id = product.id %}
product_id = {{ product.id }}
options_product_id = $('.product-options.id_'+product_id);
$options_{{ product_id }} = $('.product-options.id_{{ product_id }}');
$select_{{ product_id }} = $('select',$options_{{ product_id }});
$ul_{{ product_id }} = $('ul',$options_{{ product_id }});
function updateSelectOptionsDisabling_{{ product_id }}(){
$('option',$select_{{ product_id }}.not(':first')).attr("disabled","disabled");
for(a in product_options_{{ product_id }}[$select_{{ product_id }}.first().val()]){
$('option[value='+a+']',$select_{{ product_id }}).removeAttr("disabled","disabled");
for(b in product_options_{{ product_id }}[$select_{{ product_id }}.first().val()][a]){
$('option[value='+b+']',$select_{{ product_id }}).removeAttr("disabled","disabled");
}
}
}
/*function currencyUpdate(){
Currency.convertAll(shopCurrency, jQuery('.selected-currency').text());
}*/
function removeAbsentOption_{{ product_id }}($variant,current,$ul,$this_a){
_this=$this_a;
$inventory_management = $variant['inventory_management'];
$inventory_policy = $variant['inventory_policy'];
$inventory_quantity = $variant['inventory_quantity']
if (($inventory_management != 'shopify') ||
($inventory_management == 'shopify' && $inventory_policy == 'continue') ||
($inventory_management == 'shopify' && $inventory_quantity > 0))
{
$('a[data-value=' + current + ']', $ul).parent().removeClass('absent-option');
}
};
function showAvailableOptions_{{ product_id }}(first_option_only,last_option_only)
{
first_option_only = typeof first_option_only !== 'undefined' ? first_option_only : false;
last_option_only = typeof last_option_only !== 'undefined' ? last_option_only : false;
if(first_option_only)
{
$a = $('a', $ul_{{ product_id }}.first());
} else if(last_option_only)
{
$('li',$ul_{{ product_id }}.last()).addClass("absent-option");
$a = $('a', $ul_{{ product_id }}.last());
} else
{
$('li',$ul_{{ product_id }}).addClass("absent-option");
$a = $('a', $ul_{{ product_id }}.not(':first'));
}
$a.each(function () {
current = $(this).data('value');
_this = $(this);
for (size in product_options_{{ product_id }})
{
if(!first_option_only || last_option_only){
size=$('li.active a',$ul_{{ product_id }}.first()).data('value');
}
if($ul_{{ product_id }}.length == 3){
flag_ignore_selection = false;
for (color in product_options_{{ product_id }}[size])
{
if(last_option_only){
color=$('li.active a',$ul_{{ product_id }}.not(':first').not(':last')).data('value');
}
for (material in product_options_{{ product_id }}[size][color])
{
switch (_this.closest('ul').data('index')) {
case 0:
if (product_options_{{ product_id }}[current] != undefined && product_options_{{ product_id }}[current][color] != undefined && product_options_{{ product_id }}[current][color][material] != undefined) {
removeAbsentOption_{{ product_id }}(product_options_{{ product_id }}[current][color][material],current,$ul_{{ product_id }},_this);
}
break;
case 1:
if (product_options_{{ product_id }}[size] != undefined && product_options_{{ product_id }}[size][current] != undefined && product_options_{{ product_id }}[size][current][material] != undefined) {
removeAbsentOption_{{ product_id }}(product_options_{{ product_id }}[size][current][material],current,$ul_{{ product_id }},_this);
}
break;
case 2:
if (product_options_{{ product_id }}[size] != undefined && product_options_{{ product_id }}[size][color] != undefined && product_options_{{ product_id }}[size][color][current] != undefined) {
removeAbsentOption_{{ product_id }}(product_options_{{ product_id }}[size][color][current],current,$ul_{{ product_id }},_this);
}
break;
}
}
}
}
else if($ul_{{ product_id }}.length == 2)
{
for (color in product_options_{{ product_id }}[size]) {
switch (_this.closest('ul').data('index')) {
case 0:
if (product_options_{{ product_id }}[current] != undefined && product_options_{{ product_id }}[current][color] != undefined) {
removeAbsentOption_{{ product_id }}(product_options_{{ product_id }}[current][color], current, $ul_{{ product_id }},_this);
}
break;
case 1:
if (product_options_{{ product_id }}[size] != undefined && product_options_{{ product_id }}[size][current] != undefined) {
removeAbsentOption_{{ product_id }}(product_options_{{ product_id }}[size][current], current, $ul_{{ product_id }},_this);
}
break;
}
}
}
else
{
if (product_options_{{ product_id }}[current] != undefined) {
removeAbsentOption_{{ product_id }}(product_options_{{ product_id }}[current],current,$ul_{{ product_id }},_this);
}
}
}
})
}
function renderSwatches_{{ product_id }}()
{
showAvailableOptions_{{ product_id }}(); //2nd and 3rd
showAvailableOptions_{{ product_id }}(true); //1st only
$('li.active.absent-option',$ul_{{ product_id }}).each(function(){
$(this).removeClass('active').siblings().not('.absent-option').first().addClass('active');
});
showAvailableOptions_{{ product_id }}(false,true); //1st only
$('li.active.absent-option',$ul_{{ product_id }}).each(function(){
$(this).removeClass('active').siblings().not('.absent-option').first().addClass('active');
});
}
$(function($) {
{% unless product_options == 'swatches' %}updateSelectOptionsDisabling_{{ product_id }}();{% endunless %}
$select_{{ product_id }}.first().addClass('first');
$ul_{{ product_id }}.first().addClass('first');
$select_{{ product_id }}.change(function(){
{% unless product_options == 'swatches' %}updateSelectOptionsDisabling_{{ product_id }}();{% endunless %}
if($(this).hasClass('first'))
{
for (var first_option_to_select in product_options_{{ product_id }}[$select_{{ product_id }}.first().val()])break;
$('option',$select_{{ product_id }}.not(':first')).removeAttr("selected");
$('option[value='+first_option_to_select+']',$select_{{ product_id }}.not(':first')).attr("selected","selected");
}
updateData('select',product_id,options_product_id);
Currency.convertAll('{{ shop.currency }}', Currency.cookie.read());
})
{% if product_options == 'swatches' %}
$('a',$ul_{{ product_id }}).click(function(e){
_this = $(this);
if(!_this.parent().hasClass('absent-option')){
if (!_this.parent('li').is('.active')){
_this.closest('ul').find('li').removeClass('active');
_this.parent('li').addClass('active');
}
renderSwatches_{{ product_id }}();
$this=$('ul.color-list:first > li.active:first > a:first',$options_{{ product_id }});
if($this.data('image')){
var $image = $('.main-image img',$ul_{{ product_id }});
imgSrc = $this.data('image');
var newImg = document.createElement("img");
newImg.src = imgSrc;
newImg.onload = function () {
$image.attr('src', imgSrc);
$image.attr('data-zoom-image', imgSrc);
}
}
updateData('ul > li.active > a',{{ product_id }},$options_{{ product_id }});
Currency.convertAll('{{ shop.currency }}', Currency.cookie.read());
}
e.preventDefault();
})
renderSwatches_{{ product_id }}();
{% endif %}
});
</script>
{{ 'custom.js' | asset_url | script_tag }}
Within there I can kinda of see that this code is what displays the variants but I can't figure out how to break up each variant to be able to display them individually.
<div class="product-size option-{{ option | handle }} {{ product_options }}">
<span class="option-label">{{ option }}:</span>
<div class="select-wrapper-sm">
<select class="form-control input-sm size-variants">
{% for name in option_names %}
<option {% if selected_value == name %}selected="selected"{% endif %} value="{{ name | handle | downcase | escape }}">{{ name }}</option>
{% endfor %}
</select>
</div>
{% if product_options == 'swatches' %}
<ul class="{% if option_title contains 'color' %}color-list{% else %}size-list{% endif %}" data-index="{{ forloop.index0 }}">
{% for name in color_image %}
{%- assign title = name | split:':' | first | replace:'!__!','' -%}
{%- assign img_src = name | split:':' | last -%}
<li {% if selected_value == title %}class="active"{% endif %}>
{% if option_title contains 'color' %}<span class="value"><img src="{% if settings.product_previews_colors_variants %}{{ img_src }}{% else %}{{ title | handle | prepend:'color-' | append: '.png' | file_url | downcase }}{% endif %}" alt=""></span>{% else %}{{ title | escape }}</span>{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
Any help is appreciated. I'm looking to just brake them up so i can style them individually with tabs. I can manage all the rest by studying more. This has just stumped me.
I was able to find this code which outputs what I need but I can't seem to make them clickable to make them an option
{% for option in product.options %}
{% if option == 'Size' %}
{% assign index = forloop.index0 %}
{% assign sizelist = '' %}
{% assign size = '' %}
{% for variant in product.variants %}
{% capture size %}
{{ variant.options[index] }}
{% endcapture %}
{% unless sizelist contains size %}
<span>{{ size }}</span>
{% capture tempList %}
{{sizelist | append: size | append: ' '}}
{% endcapture %}
{% assign sizelist = tempList %}
{% endunless %}
{% endfor %}
{% endif %}
{% endfor %}
You may use a loop through product.variants object:
{% for variant in product.variants %}
What you need to do with variant.
{% endfor %}

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.

jQuery datetimepicker- unable to select date from next year

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?

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();

Categories

Resources