How to use "django-autocomplete-light" in inline form - javascript

I would like to use an inline model form with a 'django-autocomplete-light field'. I'm a little bit desperate also, because I don't know 'javascript' well.
This is a picture of my form. At first glance, it works as desired:
Unfortunately, only the first field loads correctly. If I add more fields there are errors (see pictures).
This is my form template where I suspect the error, because the first field works correctly as desired.
<div class="container">
<form method="post" action="">
{% csrf_token %}
{{ form.as_p }}
<!-- Medication Table -->
<table class="table">
{{ medication.management_form }}
{% for form in medication.forms %}
{% if forloop.first %}
<thead>
<tr>
{% for field in form.visible_fields %}
<th>{{ field.label|capfirst }}</th>
{% endfor %}
</tr>
</thead>
{% endif %}
<tr class="{% cycle "row1" "row2" %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" value="Submit Form"/>
<script type="text/javascript" src="{% static '/js/core/jquery.3.2.1.min.js' %}"></script>
{{ form.media }}
<!-- script for add, delete, update -->
<script src="{% static 'formset/jquery.formset.js' %}"></script>
<script type="text/javascript">
$('.formset_row').formset({
addText: 'add medication',
deleteText: 'remove',
prefix: 'medication_set'
});
</script>
</div>

After hours googling and going through other answers, what worked for me was this.
I added a key named clone in the defaults of the jquery.formset.js with default value as true.
/* Setup plugin defaults */
$.fn.formset.defaults = {
prefix: 'form', // The form prefix for your django formset
formTemplate: null, // The jQuery selection cloned to generate new form instances
clone: true, // Set this value to false when using autocomplete in formset
addText: 'add another', // Text for the add link
deleteText: 'remove', // Text for the delete link
addCssClass: 'add-row', // CSS class applied to the add link
deleteCssClass: 'delete-row', // CSS class applied to the delete link
formCssClass: 'dynamic-form', // CSS class applied to each form in a formset
extraClasses: [], // Additional CSS classes, which will be applied to each form in turn
keepFieldValues: '', // jQuery selector for fields whose values should be kept when the form is cloned
added: null, // Function called each time a new form is added
removed: null // Function called each time a form is deleted
};
Then replaced the code inside addButton.click() in jquery.formset.js from
row = options.formTemplate.clone(true).removeClass('formset-custom-template')
to
row = options.formTemplate.clone(options.clone).removeClass('formset-custom-template')
Then in the template of the formset, changed formset function from this :
$('#brand_formset_div .parentdiv .form-group').formset({
prefix: '{{ brand_formset.prefix }}',
deleteText: 'Clear',
deleteCssClass: 'shop-now-delete',
addText: 'Add new Brand',
addCssClass: 'btn btn-success ',
});
to this (a clone key as false is inserted along with a function added that is triggered when a new row is inserted.The function hides the extra autocomplete box.)
$('#brand_formset_div .parentdiv .form-group').formset({
prefix: '{{ brand_formset.prefix }}',
clone: false,
deleteText: 'Clear',
deleteCssClass: 'shop-now-delete',
addText: 'Add new Brand',
addCssClass: 'btn btn-success ',
added: function(row) {
$('span .select2-selection--single:odd', row || null).css("display", "none");
}
});
This worked fine for me.

Related

How to populate checkboxes in a table with values from a Django model

My html table has a column that contains a checkbox. The user can check or uncheck it. The value (boolean) is stored in the Django model Subscriber under Subscriber.participates. All objects of Subscriber are imported into the HTML using a Django view (context = {'subscribers' : Subscriber.objects.all(),}).
When loading the table, the checkboxes must be set to the correct value. To that purpose I have written a javascript function, which is invoked in the <input> element. However, the checkboxes all remain unchecked, though I have verified through /admin/ in Django that some of the values in the dbase are indeed "TRUE". firstName and lastName load without any problem into the table. What did I do wrong?
<head>
<meta charset="UTF-8">
<title>Participants</title>
<script>
function checkBox() {
if({{ x.participates }}){
document.getElementById("checkbox").checked = true;
} else {
document.getElementById("checkbox").checked = false;
}
}
</script>
</head>
<body>
<table>
{% for x in subcribers %}
<tr>
<form action="updateSuscribers/{{ x.id }}" method="post">
{% csrf_token %}
<td>{{ x.firstName }}</td>
<td>{{ x.lastName }}</td>
<td>
<input id="checkbox" type="checkbox" name="participates" onload="checkBox()">
</td>
</form>
</tr>
{% endfor %}
</table>
</body>
you don't need a js function to render existing data with the Checked/Unchecked Box.
assuming boolean field name is_subscribed
{% for sub in subscribers %}
{% if sub.is_subscribed %}
<input type="checkbox" checked>
{% else %}
<input type="checkbox">
{% endif %}
{% endfor %}
but Yes you gonna need js click event if you want it to update using the Click on Realtime without Refreshing page

Unable to pass variant data into shopify form

I am trying to pass through variant JSON data using a data-variants attribute into an add to cart form, but i cant refactor correctly to work with Shopifys more up to date form syntax.
<form id="add-to-cart-form" action="/cart/add" method="post" enctype="multipart/form-data" data-variants="{{variants_with_quantity_json | url_param_escape }}"></form>
{% form 'product', product, data-product-form: '', data-product-handle: product.handle, data-enable-history-state: 'true', id: "add-to-cart-form" %}
The data variant attribute simply outputs the object with no data in my version.
But i need the data to bee accessible on the form like so;
I am trying to add the invetory qty to the product.variants.json and need to figure out how {{ variants_with_quantity_json }} can be passed to the form.
{% assign variants_with_quantity_json = product.variants | json %}
{% unless variants_with_quantity_json contains 'inventory_quantity' %}
{% for variant in product.variants %}
{% assign replace_hook_variant_id = '"id":' | append:variant.id %}
{% assign replace_id_plus_inventory = replace_hook_variant_id | append: ',' | append: '"inventory_quantity":' |
append: variant.inventory_quantity %}
{% assign variants_with_quantity_json = variants_with_quantity_json | replace: replace_hook_variant_id,
replace_id_plus_inventory %}
{% endfor %}
{% endunless %}
okay, you need to assign the data to a variable before pass it to {% form %} in Shopify
So you {% form %} look like this:
{% assign data_variants = variants_with_quantity_json | url_param_escape %}
{% form 'product', product, data-product-form: '', data-product-handle: product.handle, data-enable-history-state: 'true', id: "add-to-cart-form" data-variants: data_variants %}
or you may use the {% capture %} liquid code tag to get and pass the value
{% capture 'data_variants' %}variants_with_quantity_json | url_param_escape{% endcapture %}
{% form 'product', product, data-variants: data_variants %}
...
{% endform %}

How to get only checked elements from a form in shopify?

{% assign type_bonbon = "Sans sucre, Gélifié, Guimauve, Nougat, Acide, Doux" | split : ", " %}
<section class="page__content">
{% capture contact_form %}
<div class="contact">
{% form 'contact', class: 'contact__form' %}
<div class="form__control">
<label class = "form__label" for="contact__type_bonbon">Types de bonbons</label>
{% for type in type_bonbon %}
<div class = "checkbox">
<input type="checkbox" id="contact__type_bonbon" name="contact[type]" value="{{type_bonbon}}">{{type}}
</div>
{% endfor %}
</div>
{% endform %}
</div>
{% endcapture %}
</section>
Hello everyone,
I am struggling to Get every checked values within the checkbox.
Right now im getting only the last checked value
I know in PHP we would use the GET method in order to put the "checked" method to every checkbox checked, however, idk how to proceed in shopify.
Thank you again
I just checked and I was able to replicate the behavior that you mentioned above about receiving only the last checked value. I don't know if it is a bug or feature from Shopify, but you can use a workaround like below where each field is named differently. Another minor thing is the ID attribute needs to be unique while it generates the same in your for loop above. Besides, that for value it should have been value="{{type}}" instead of value="{{type_bonbon}}" as type_bonbon is an array.
{% assign type_bonbon = "Sans sucre, Gélifié, Guimauve, Nougat, Acide, Doux" | split : ", " %}
<section class="page__content">
{% capture contact_form %}
<div class="contact">
{% form 'contact', class: 'contact__form' %}
<div class="form__control">
<label class = "form__label" for="contact__type_bonbon">Types de bonbons</label>
{% for type in type_bonbon %}
<div class = "checkbox">
<input type="checkbox" name="contact[type-{{type}}]" value="{{type}}">{{type}}
</div>
{% endfor %}
</div>
{% endform %}
</div>
{% endcapture %}
</section>
Only this line of code is changed, to generate new field name for each type.
<input type="checkbox" name="contact[type-{{type}}]" value="{{type}}">{{type}}

How to pass the data through button using unique id in a dynamic table

i am using django and bootstrap and i want to pass data through button and show that data on bootstrap popup modal and i want that in each loop x.bots data should be passed uniquely so that i can access bot title ,bot id
using another loop at x.bots
{% for x in data %}
<td>{% if x.bots %} Show Bots {{ x.bots|length }}{% endif %}</td>
{% endfor %}
this is my script file
<script>
$(document).on('show.bs.modal','#myModal', function (event) {
var button = $(event.relatedTarget);
var recipient = button.data(x.bots);
var modal = $(this);
modal.find('.modal-title').text('Bots Title');
modal.find('.modal-body input').val(i);
})
</script>
but i tried alot using different ways but not getting the data
You can try something like this. Use an onclick javascript function and pass the parameters you want to use.
{% for x in data %}
<td>{% if x.bots %}<a href="#myModal" class="btn btn-primary btn-sm" data-toggle="modal" data="x.bots"
onclick="myFunction({{ x.bots.title }} , {{ x.bots.id }})"> Show Bots
{{ x.bots|length }}{% endif %}</a></td>
{% endfor %}
Then in the script implement the javascript function.
function myFunction(title, id) {
//write code here
}
It seems to me that var modal = $(this); will not result in an element since I don't see this defined anywhere.
Maybe change it to var modal = $('#myModal'); or var modal = event.target?
Change this
{% for x in data %}
<td>{% if x.bots %} Show Bots {{ x.bots|length }}{% endif %}</td>{% endfor %}
To This,
{% for x in data %}
<td>{% if x.bots %} Show Bots {{ x.bots|length }}{% endif %}</td>{% endfor %}

django bootstrap datetimepicker

i am trying to implement the datepicker using the django bootstrap datepicker widget, but the datepicker is not showing on the webpage ("welcome.html)
i have passed the form to the views and called the form in the webpage
any help will be appreciated
forms.py
class DateForm(forms.Form):
todo = forms.CharField(
widget=forms.TextInput(attrs={"class":"form-control"}))
date_1=forms.DateField(widget=DatePicker(
options={"format": "mm/dd/yyyy",
"autoclose": True }))
def cleandate(self):
c_date=self.cleaned_data['date_1']
if c_date < datetime.date.today():
raise ValidationError(_('date entered has passed'))
elif c_date > datetime.date.today():
return date_1
def itamdate(self):
date_check=calendar.setfirstweekday(calendar.SUNDAY)
if c_date:
if date_1==date_check:
pass
elif date_1!=date_check:
raise ValidationError('The Market will not hold today')
for days in list(range(0,32)):
for months in list(range(0,13)):
for years in list(range(2005,2108)):
continue
views.py
def imarket(request):
#CREATES A FORM INSTANCE AND POPULATES USING DATE ENTERED BY THE USER
if request.method=='POST':
form = DateForm(request.POST or None)
#checks validity of the form
if form.is_valid():
itamdate=form.cleaned_data['date_1']
return HttpResponseRedirect(reverse('welcome.html'))
return render(request, 'welcome.html', {'form':form})
welcome.html
{% extends 'base.html' %}
{% load bootstrap %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="//cdn.bootcss.com/bootstrap-datetimepicker/4.17.44/js/bootstrap-datetimepicker.min.js"></script>
{% block content %}
<title>welcome</title>
<form action = "{% url "imarket"}" method = "POST" role="form">
{% csrf_token %}
<table>
{{form|bootstrap_horizontal}}
</table>
<div class = "form-group">
<input type ="submit" value= "CHECK" class="form control"/>
</div>
</form>
{% endblock %}
The bootstrap datepicker wasn't working , so i added the jquery datepicker to directly to my forms. py using this answer
my updated forms.py
class DateForm(forms.Form):
todo = forms.CharField(
widget=forms.TextInput(attrs={"class":"form-control"}))
date_1=forms.DateField(widget=forms.DateInput(attrs={'class':'datepicker'}))
my updated welcome.html
{% extends 'base.html' %}
{% load bootstrap %}
{% block content %}
<title>welcome</title>
<form action = "{% url "imarket"}" method = "POST" role="form">
{% csrf_token %}
<table>
{{form|bootstrap}}
<script>
$(document).ready(function() {
$('.datepicker').datepicker();
});
</script>
</table>
<div class = "form-group">
<input type ="submit" value= "CHECK" class="form control"/>
</div>
</form>
{% endblock %}
datepicker should be initialized in the html page.
if you are using bootstrap download datepicker from Datetimepicker for Bootstrap 4
then
in the head section include
font awesome css
boostrap4 css
bootstrap-datetimepicker.min.css
in the body section include
moment.min.js
bootstrap.min.js
bootstrap-datetimepicker.min.js
define your form
from django import forms
class DateRangeForm(forms.Form):
start_date = forms.DateTimeField(required=True)
end_date = forms.DateTimeField(required=True)
in the template render the form
<form action="/your-name/" method="post">
{% csrf_token %}
{{ dt_range_form }}
<input class="btn btn-primary btn-sm" type="submit" value="Refresh">
</form>
in the script section add
$("#id_start_date").datetimepicker();
And here you have your datetimepicker! For me Time icon is still not showing up! Need to debug it.

Categories