Adding Django MultipleChoiceField one after the other using Javascript - javascript

I am working on a Django views based on the following form:
class MyForm(forms.Form):
def __init__(self, data, examen, *args, **kwargs):
super(MyForm, self).__init__(data, *args, **kwargs)
self.fields['q1'] = forms.MultipleChoiceField(
label=mark_safe("Label question 1"),
required=True,
widget=forms.CheckboxSelectMultiple,
choices=(('1', 'answer 1'), ('2', 'answer 2'), ('3', 'answer 3'))
)
self.fields['q2'] = forms.MultipleChoiceField(
label=mark_safe("Label question 2"),
required=True,
widget=forms.CheckboxSelectMultiple,
choices=(('1', 'answer 4'), ('2', 'answer 5'), ('3', 'answer 6'))
)
... #TODO : add questions q3 to q9
self.fields['q10'] = forms.MultipleChoiceField(
label=mark_safe("Label question 10"),
required=True,
widget=forms.CheckboxSelectMultiple,
choices=(('1', 'answer 28'), ('2', 'answer 29'), ('3', 'answer 30'))
)
Il would like to display on a single view self.fields['q1'] with a [submit] button. The idea is for the user to select the answer he considers as correct and the hit the [submit] button. Following that self.fields['q1'] will turn into read-only and self.fields['q2'] will display just below with again a [submit] button... and son on until self.fields['q10'].
I do believe that the only way to achieve that is to use Javascript (and even JQuery or any other library). The problem is that I'm not very familiar with Javascript and would gladly appreciate hints on how to tackle that issue.
Thank you for what you can do!
PS: I'm happy to change my Django design if you think this is not the proper way to achieve my goal.
EDIT 29/11/2019: my current template looks like:
<form action="{% url 'quizz' my_exam %}" method="post">
{% csrf_token %}
{% for field in form %}
{% ifequal forloop.counter0 0 %}
<div class="card text-white bg-primary mb-3">
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
</div>
</div>
{% else %}
<div class="card">
<h5 class="card-header">{{field.name}}</h5>
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
<p class="card-text">{{ field }}</p>
</div>
</div>
{% endifequal %}
{% endfor %}
<input type="submit" value="Submit" class="btn btn-primary"/>
</form>
EDIT 30/11/2019: new template based on #Phanti suggestions:
<script>
{% block jquery %}
$("#submit_2").click(function() {
$("#questions_container").find(":hidden").show().next();
}
{% endblock %}
</script>
{% block content %}
<form action="{% url 'quizz' exam %}" method="post">
{% csrf_token %}
<div id="questions_container">
{% for field in form %}
{% ifequal forloop.counter 1 %}
<div class="card text-white bg-primary mb-3">
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
</div>
</div>
{% else %}
{% ifequal forloop.counter 2 %}
<div id="question_{{ forloop.counter }}" class="card" style="display: block;">
<h5 class="card-header">{{field.name}}</h5>
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
<p class="card-text">{{ field }}</p>
</div>
</div>
<input id="submit_{{ forloop.counter }}" value="Valider" class="btn btn-primary" style="display: block;"/>
{% else %}
<div id="question_{{ forloop.counter }}" class="card" style="display: none;">
<h5 class="card-header">{{field.name}}</h5>
<div class="card-body">
<h6 class="card-title">{{ field.label|linebreaksbr }}</h6>
<p class="card-text">{{ field }}</p>
</div>
</div>
{% if not forloop.last %}
<input id="submit_{{ forloop.counter }}" value="Submit" class="btn btn-primary" style="display: none;"/>
{% else %}
<input id="submit_{{ forloop.counter }}" type="submit" value="Submit" class="btn btn-primary" style="display: none;"/>
{% endif %}
{% endifequal %}
{% endifequal %}
{% endfor %}
</div>
</form>
{% endblock %}

Related

Django and waypoints Infinite scroll not working

I have tried all the answers on stack and the infinite scroll is still not working. My home.html is still displaying the pagination. I suspect the problem is with jquery or the js files or with how the static file is loaded?
Here is my home.html:
{% block content %}
{% load static %}
<div class="infinite-container">
{% for post in posts %}
<div class="infinite-item">
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
<small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small>
</div>
<h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
</div>
{% endfor %}
</div>
<div class="d-flex d-none position-fixed" style="top:35vh;left:46vw">
<button class="btn btn-primary loading">
<span class="spinner-border spinner-border-sm"></span>
Please wait...
</button>
</div>
<!--pagination logic -->
<div class="col-12">
{% if page_obj.has_next %}
<a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}">next</a>
{% endif %}
</div>
<script src="/static/js/jquery.waypoints.min.js"></script>
<script src="/static/js/infinite.min.js"></script>
<script>
var infinite = new Waypoint.Infinite({
element: $('.infinite-container')[0],
offset: 'bottom-in-view',
onBeforePageLoad: function () {
$('.loading').show();
},
onAfterPageLoad: function () {
$('.loading').hide();
}
});
</script>
{% endblock content %}
In my settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [Path(BASE_DIR, 'static'),]
The directory of my js files.
I have added the following within my base.html at the bottom.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
here is my class based view in view.py:
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted']
paginate_by = 5

Shopify Store Refresh cart content. AJAX request

I have product page on which I have shop now btn. When user clicks on this button, page opens cart drawer with custom ajax template content.
I rewrited click event with my own logic. I use AJAX and send request for adding product by myself. Products are adding but is not showing in the cart drawer. Only after reloading page it is appearing.
Question is to can I refresh cart content? I'm trying to past content template via inner html. But it is looks like not liquid format.
Here is the template
<script id="CartTemplate" type="text/template">
{% render 'banana-stand-cart-top-container' %}
{% raw %}
<div class="drawer__scrollable">
{{#items}}
<div class="ajaxcart__product appear-animation appear-delay-{{animationRow}}">
<div class="ajaxcart__row">
<div class="grid">
<div class="grid__item one-third">
<img src="{{img}}" alt="{{name}}">
</div>
<div class="grid__item two-thirds">
<div class="ajaxcart__product-name--wrapper">
{{{name}}}
{{#if variation}}
<div class="ajaxcart__product-meta">{{variation}}</div>
{{/if}}
{{#if selling_plan_name}}
<div class="ajaxcart__product-meta">{{selling_plan_name}}</div>
{{/if}}
{{#properties}}
{{#each this}}
{{#if this}}
<span class="ajaxcart__product-meta">{{#key}}: {{this}}</span>
{{/if}}
{{/each}}
{{/properties}}
</div>
<div class="grid grid--full display-table">
<div class="grid__item display-table-cell one-half">
<label for="updates_{{key}}" class="visually-hidden">{% endraw %}{{ 'products.product.quantity' | t }}{% raw %}</label>
<div class="js-qty__wrapper">
<input type="text" id="updates_{{key}}"
class="js-qty__num"
value="{{itemQty}}"
data-id="{{key}}"
min="0"
aria-label="quantity"
pattern="[0-9]*"
name="updates[]">
<button type="button"
class="js-qty__adjust js-qty__adjust--minus"
aria-label="{% endraw %}{{ 'cart.general.reduce_quantity' | t }}{% raw %}">
{% endraw %}<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-minus" viewBox="0 0 20 20"><path fill="#444" d="M17.543 11.029H2.1A1.032 1.032 0 0 1 1.071 10c0-.566.463-1.029 1.029-1.029h15.443c.566 0 1.029.463 1.029 1.029 0 .566-.463 1.029-1.029 1.029z"/></svg>{% raw %}
<span class="icon__fallback-text" aria-hidden="true">−</span>
</button>
<button type="button"
class="js-qty__adjust js-qty__adjust--plus"
aria-label="{% endraw %}{{ 'cart.general.increase_quantity' | t }}{% raw %}">
{% endraw %}<svg aria-hidden="true" focusable="false" role="presentation" class="icon icon-plus" viewBox="0 0 20 20"><path fill="#444" d="M17.409 8.929h-6.695V2.258c0-.566-.506-1.029-1.071-1.029s-1.071.463-1.071 1.029v6.671H1.967C1.401 8.929.938 9.435.938 10s.463 1.071 1.029 1.071h6.605V17.7c0 .566.506 1.029 1.071 1.029s1.071-.463 1.071-1.029v-6.629h6.695c.566 0 1.029-.506 1.029-1.071s-.463-1.071-1.029-1.071z"/></svg>{% raw %}
<span class="icon__fallback-text" aria-hidden="true">+</span>
</button>
</div>
</div>
<div class="grid__item display-table-cell one-half text-right">
{{#if discountsApplied}}
<small class="cart__price--strikethrough">{{{price}}}</small>
<span class="ajaxcart__price">
{{{discountedPrice}}}
</span>
{{else}}
<span class="ajaxcart__price">
{{{price}}}
</span>
{{/if}}
</div>
</div>
<div class="grid grid--full display-table">
{{#if discountsApplied}}
<div class="grid__item text-right">
{{#each discounts}}
<small class="ajaxcart__discount cart__discount">
{{this.discount_application.title}} (-{{{this.formattedAmount}}})
</small>
{{/each}}
</div>
{{/if}}
{{#if unitBase}}
<div class="grid__item text-right">
<div class="product__unit-price">
{{{ unitPrice }}}/{{{ unitBase }}}
</div>
</div>
{{/if}}
</div>
</div>
</div>
</div>
</div>
{{/items}}
{% endraw %}{% if settings.cart_notes_enable %}{% raw %}
<div class="appear-animation appear-delay-{{lastAnimationRow}}">
<label for="CartSpecialInstructions" class="ajaxcart__note">{% endraw %}{{ 'cart.general.note' | t }}{% raw %}</label>
<textarea name="note" class="input-full cart-notes" id="CartSpecialInstructions">{{note}}</textarea>
</div>
{% endraw %}{% endif %}{% raw %}
</div>
<div class="drawer__footer appear-animation appear-delay-{{lastAnimationRow}}">
{{#if cartDiscounts }}
<div class="grid grid--full">
<div class="grid__item one-half">
<p class="ajaxcart__subtotal">{% endraw %}{{ 'cart.general.discounts' | t }}{% raw %}</p>
</div>
<div class="grid__item one-half text-right">
{{#each cartDiscounts}}
<p class="ajaxcart__price cart__discount">
{{this.title}} (-{{{this.formattedAmount}}})
</p>
{{/each}}
</div>
</div>
{{/if}}
<div class="grid grid--full">
<div class="grid__item one-half">
<p class="ajaxcart__subtotal">{% endraw %}{{ 'cart.general.subtotal' | t }}{% raw %}</p>
</div>
<div class="grid__item one-half text-right">
<p class="ajaxcart__price"><span class="tdf-cart-total-parent">{{totalPrice}}</span></p>
</div>
</div>
<p class="ajaxcart__note">
{% endraw %}{{ 'cart.general.shipping_at_checkout' | t }}{% raw %}
</p>
{% endraw %}{% if settings.cart_terms_conditions_enable %}
<p class="ajaxcart__note ajaxcart__note--terms">
<input type="checkbox" id="CartAgree" />
<label for="CartAgree">
{% if settings.cart_terms_conditions_link != blank %}
{{ 'cart.general.terms_html' | t: url: settings.cart_terms_conditions_link }}
{% else %}
{{ 'cart.general.terms' | t }}
{% endif %}
</label>
</p>
{% endif %}{% raw %}
{% endraw %}
{% if additional_checkout_buttons and settings.cart_additional_buttons %}
<div class="additional-checkout-buttons additional-checkout-buttons--vertical">{{ content_for_additional_checkout_buttons }}</div>
{% endif %}
{% raw %}
<button type="submit" class="btn btn--full cart__checkout{% endraw %}{% if settings.cart_terms_conditions_enable %}{% raw %} cart__checkout--ajax{% endraw %}{% endif %}{% raw %}" name="checkout">
{% endraw %}{{ 'cart.general.checkout' | t }}{% raw %}
</button>
</div>
{% endraw %}
Usually, there is some way (js-function) that allows you to rebuild the cart with new items.
You need to check the js-code that is responsible for showing the drawer-cart
So, need fire some event that you can find in your theme.js file. In my case I needed to add this:
document.dispatchEvent(new CustomEvent('cart:build', {
detail: {
cart: cart
}
}));

jQuery widgets not working for dynamically added formset forms

I have a form and a related formset in my view/template. For several fields I use widgets: Select2 and a calendar (date-picker) from django admin app.
I also use dynamic addition of formset forms.
When I render a template for the first time, all widgets work fine. But when I add new formset form, widgets of this new form don't work.
I've read existing questions on this kind of problem: 1, 2, 3, 4, but they either not applicable for me, or not helping (2 and 3), or may be I am just doing something wrong (most likely - I'm new to it).
Much appreciated for any tips.
HTML:
{% extends "docs/base.html" %}
{% load static %}
{% block extrahead %}
{{ block.super }}
{{ form_matter.media.css }}
<link href="/static/django_select2/select2.min.css" type="text/css" media="screen" rel="stylesheet">
{% endblock %}
{% block content %}
{% if mat_id == None %}
<form id="MatterForm" action="{% url 'matter_create_url' %}" enctype="multipart/form-data" method="post">
{% else %}
<form id="MatterForm" action="{% url 'matter_edit_url' mat_id=mat_id %}" enctype="multipart/form-data" method="post">
{% endif %}
{% csrf_token %}
<fieldset>
{% for field in form_matter %}
<div class="form-row">
{% if field.errors %}
<div>{{ field.errors }}</div>
{% endif %}
<label class="form-label">{{ field.label_tag }}</label>
<div class="form-input">{{ field }}</div>
</div>
{% endfor %}
<h3>RESOLUTIONS</h3>
<div id="form_set">
{{ formset_resolutions.management_form }}
{% for form in formset_resolutions %}
<div class="formset-form">
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
<div class="form-row">
{% if field.errors %}
<div>{{ field.errors }}</div>
{% endif %}
<label class="form-label">{{ field.label_tag }}</label>
<div class="form-input">{{ field }}</div>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
</fieldset>
<br>
<button class="btn" type="button" id="add_form" style="margin: 0 0 0 25px">ADD</button>
<button class="btn" type="submit" style="margin: 0 0 0 25px">SAVE</button>
<br><br><br>
<div id="empty_form" style="display:none">
<div class="formset-form">
{% for field in formset_resolutions.empty_form.visible_fields %}
<div class="form-row">
{% if field.errors %}
<div>{{ field.errors }}</div>
{% endif %}
<label class="form-label">{{ field.label_tag }}</label>
<div class="form-input">{{ field }}</div>
</div>
{% endfor %}
</div>
</div>
</form>
<script type="text/javascript">window.__admin_media_prefix__ = "{% static 'admin/' %}";</script>
<script type="text/javascript" src="/jsi18n/"></script>
<script type="text/javascript" src="/static/js/jquery.js"></script>
<script type="text/javascript" src="/static/django_select2/select2.min.js"></script>
<script>
$('#add_form').on('click', function() {
var form_idx = $('#id_resolution_set-TOTAL_FORMS').val();
$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_resolution_set-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
<script>$('div.form-row:has(label.form-label:has(label[for$="-DELETE"]))').css('background-color', '#ffc7c7')</script>
{{ form_matter.media.js }}
{% endblock content %}

How to manage a PHP list with javascript trigger

I'm on a php(symfony4)/twig application. On a part which dynamically show a list of alerts in php.
I need to put checkboxes to manage this list (show/hide some alerts).
twig file :
<div class="x_title" style="display: flex">
<h2 class="text-uppercase">
<span id="nbAlerts">-</span> alerte(s)
</h2>
<div class="clearfix"></div>
<label class="container-checkbox">Required action
<input type="checkbox" checked="checked" id="red_action">
<span class="checkmark checkMarkRed"></span>
</label>
<label class="container-checkbox">Major action
<input type="checkbox" checked="checked" id="orange_action">
<span class="checkmark checkMarkOrange"></span>
</label>
<label class="container-checkbox">Action mineure
<input type="checkbox" checked="checked" id="yellow_action">
<span class="checkmark checkMarkYellow"></span>
</label>
</div>
<div class="x_content">
<div id="AlertListContainer">
/* place where the alerts' list is dynamically appears */
</div>
</div>
AlertList file
{% if toAlert is empty %}
no alert to display
{% else %}
<ul class="to_do">
{% for oAlert in toAlert %}
{% set alertColor = '' %}
{% if oAlert.type.level.label == 'High' %}
{% set alertColor = 'red' %}
{% elseif oAlert.type.level.label == 'Medium' %}
{% set alertColor = 'orange' %}
{% elseif oAlert.type.level.label == 'Low' %}
{% set alertColor = 'yellow' %}
{% endif %}
<li class="border_{{ alertColor }}"
onclick="window.location.href='{{ oAlert.link }}'">
<p class="tag-notif text-uppercase text-center">
{{ oAlert.type.level.label }}
</p>
<p class="text-notif">
{{ oAlert.content }}
</p>
</li>
{% endfor %}
</ul>
{% endif %}
So, when only the "required action" checkbox is checked, i want to see only the alerts : oAlert.type.level.label == 'High'.
I did it this in my javascript, but i know it's wrong...
$(function () {
$("#red_action").click(function () {
if ($(this).is(":checked")) {
$({{oAlert.type.level.label == 'High'}}).show();
} else {
$({{oAlert.type.level.label == 'High'}}).hide();
}
});
});
i did't find better approch that doesn't change your code so much so i wrote this , this will work if don't then do some tweaks
<div class="x_title" style="display: flex">
<h2 class="text-uppercase">
<span id="nbAlerts">-</span> alerte(s)
</h2>
<div class="clearfix"></div>
<label class="container-checkbox">Required action
<input type="checkbox" checked="checked" id="red_action" data-checkcolor="red">
<span class="checkmark checkMarkRed"></span>
</label>
<label class="container-checkbox">Major action
<input type="checkbox" checked="checked" id="orange_action" data-checkcolor="orange">
<span class="checkmark checkMarkOrange"></span>
</label>
<label class="container-checkbox">Action mineure
<input type="checkbox" checked="checked" id="yellow_action" data-checkcolor="yellow">
<span class="checkmark checkMarkYellow"></span>
</label>
</div>
<div class="x_content">
<div id="AlertListContainer">
/* place where the alerts' list is dynamically appears */
</div>
</div>
{% if toAlert is empty %}
no alert to display
{% else %}
<ul class="to_do">
{% for oAlert in toAlert %}
{% set alertColor = '' %}
{% if oAlert.type.level.label == 'High' %}
{% set alertColor = 'red' %}
{% elseif oAlert.type.level.label == 'Medium' %}
{% set alertColor = 'orange' %}
{% elseif oAlert.type.level.label == 'Low' %}
{% set alertColor = 'yellow' %}
{% endif %}
<li data-color="{{ alertColor }}" hidden class="border_{{ alertColor }}"
onclick="window.location.href='{{ oAlert.link }}'">
<p class="tag-notif text-uppercase text-center">
{{ oAlert.type.level.label }}
</p>
<p class="text-notif">
{{ oAlert.content }}
</p>
</li>
{% endfor %}
</ul>
{% endif %}
<script>
$("[data-checkcolor]").on('change',function () {
var color = $(this).attr('data-checkcolor');
if ($(this).is(":checked")) {
$("[data-color='"+color+"']").prop('hidden',false);
} else {
$("[data-color='"+color+"']").prop('hidden',true);
}
});
</script>

Long loading Javascript (modal window)

On this site http://nashedom.ru there are JS scripts. Most are fast.
The modalka fancybox pages (for login users, in user cabinet, page объявления -> добавление объявления) are very slow. In Chrome loading is 25-28 seconds. In Firefox - 2,5 seconds.
The data is taken out of context.
HTML:
{% load hosts %}
<div class="b-header">
<div class="b-header__menu">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="b-menu">
<a>...</a>
<a>...</a>
<a>...</a>
<a>...</a>
<span class="b-menu__item btn_change-location">
<a href="#change-location" class="fancybox dashed">
{% if user.is_authenticated %}
View ads on site:
{% if user.districts.all.count > 1 %}
{% for district in user.districts.all %}
{% if forloop.last %}
<span>{{ district }}</span>
{% else %}
<span>{{ district }},</span>
{% endif %}
{% endfor %}
{% else %}
{% for district in user.districts.all %}
<span>{{ district }}</span>
{% endfor %}
{% endif %}
{% if user.regions.all.count > 1 %}
{% for region in user.regions.all %}
{% if forloop.last %}
<span>{{ region }}</span>
{% else %}
<span>{{ region }},</span>
{% endif %}
{% endfor %}
{% else %}
{% for region in user.regions.all %}
<span>{{ region }}</span>
{% endfor %}
{% endif %}
{% if user.cities.all.count > 1 %}
{% for city in user.cities.all %}
{% if forloop.last %}
<span>{{ city }}</span>
{% else %}
<span>{{ city }},</span>
{% endif %}
{% endfor %}
{% else %}
{% for city in user.cities.all %}
<span>{{ city }}</span>
{% endfor %}
{% endif %}
{% else %}
View ads on site:
{% endif %}
</a>
</span>
</div>
</div>
</div>
</div>
</div>
Templates modal window
{% load hosts %}
{% load widget_tweaks static %}
<div id="change-location">
<form action="{% host_url "setlocation" host "www" %}" method="post">
{% csrf_token %}
<div id="chose-city-wrap">
<div class="b-modal__title">Select your city</div>
<p>
<div class="b-modal__item">
<span>{{ location_form.country.label }}</span>
{{ location_form.country }}
</div>
</p>
<p>
<div class="b-modal__item">
<span>{{ location_form.districts.label }}</span>
{{ location_form.districts }}
</div>
</p>
<p>
<div class="b-modal__item">
<span>{{ location_form.regions.label }}</span>
{{ location_form.regions }}
</div>
</p>
<p>
<div class="b-modal__item">
<span>{{ location_form.cities.label }}</span>
{{ location_form.cities }}
</div>
</p>
<br />
<div class="b-modal__item b-modal__item_btn">
<input class="b-btn b-btn_red" type="submit" value="Сохранить">
</div>
</div>
</form>
</div>
<!-- end snippet -->
cities download form on the page where the brakes modal window!
<fieldset>
<legend>The territory of distribution of the ads</legend>
{{ form.country|add_class:"b-input__input js-select" }}
{{ form.districts|add_class:"b-input__input js-select chosen-select" }}
{{ form.regions|add_class:"b-input__input js-select chosen-select" }}
{{ form.cities|add_class:"b-input__input js-select chosen-select" }}
{# form.geo|add_class:"b-input__input" #}
</fieldset>
As you explain it, you have a lot of data to get (countries, cities), if you do it in php, you will lock the page until you retrive all those datas.
To have a shorter loading time, you just have to make everything in js (ajax).
You load your page with the cities, countries, ... without data.
Once the page is loaded (document.ready), you call your ajax to fill your cities, countries and so on.

Categories