how to change id per form in select2 django formset - javascript

i need to increment id field forms per form
default id which django provides is id_formsetname_set-0-fieldName and 0 increment one by one
in my case named id_items_set-0-model and for second form will be id_items_set-1-model it display in inspect element source code from browser , i used this for loo script
for (var i = 0; i < 10; i++){
$("#id_items_set-"+i+"-model").select2();
}
but only worked for the first form , i dont want to use django-select2
my template looks like this
this is my snippet
<tbody class="tbody tb1 " id="form_set">
{% for item in items.forms %}
<tr class="p-0 col-12">
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.price | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.quantity | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.model | add_class:'col-12 0model model' | attr:'id:id_items_set-0-model'}}
</div>
</td>
</tr>
{% endfor %}
</tbody>
<script type="text/javascript">
$(function(){
$('.tb1 tr:last').formset({
prefix:'{{items.prefix}}',
addText:'add',
deleteText:'remove',
addCssClass:'btn btn-success',
});
})
</script>
<script type="text/javascript">
$(document).ready(function(){
for (var i = 0; i < 10; i++){
$("#id_items_set-"+i+"-model").select2();
}
})
</script>
only work for my first form then doesnt have any effect on other forms ? is there something i did wrongly in the script part please?

jquery.formset has added attribute we can call a function every time when a row created
<script type="text/javascript">
$(function(){
$('.tb1 tr:last').formset({
prefix:'{{items.prefix}}',
addText:'add',
deleteText:'remove',
addCssClass:'btn btn-success',
added:function($row){
$('.model').select2()
}
});
})
</script>

I have never worked on django .
Could you try this please .
and if you could share with us a link for real example in case this doesn't work
$(()=>{
let ids = document.querySelectorAll("[id=*'id_items_set']");
ids.forEach((element)=>{
$(element).select2();
});
});

Related

How to show a modal only once per user?

I have created a Flask application that allows different users to register and log in. For this I have implemented sessions in my code. At the fist page new users arrive at, there is a modal welcoming them to the platform. I want to be able to show this modal only once to newly registered and logged in users. Alterations of this question have been answered in Stackoverflow but I tried them all and no answer helped me out.
So here is my code:
html page:
{% extends "layout.html" %}
{% block title %}
INDEX
{% endblock %}
{% block main %}
<div id="myModal" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Welcome!</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Welcome to the index page! Here you can trade to your heart's content with us by your side!<span class="badge">By Rahul jangid</span></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<!--this closes, see what ull do -->
<button type="button" class="btn btn-primary">Move On</button>
<!--Here make sure to impplement the next fuinctionality. Look at changing the color of the popover. Also add some popovers.-->
</div>
</div>
</div>
</div>
<table class="table table-striped">
<thead>
<tr>
<th style ="color:red">Symbol</th>
<th style ="color:red">Name</th>
<th style ="color:red">Stock Shares</th>
<th style ="color:red">Price</th>
<th style ="color:red">Sum</th>
</tr>
<tbody>
{% for stock in stocks %}
<tr>
<td style ="color:red">{{stock.symbol}}</td>
<td style ="color:red">{{stock.name}}</td>
<td style ="color:red">{{stock.shares}}</td>
<td style ="color:red">{{stock.price | usd}}</td>
<td style ="color:red">{{stock.total | usd}}</td>
</tr>
{% endfor %}
<tr>
<td style ="color:red">CASH</td>
<td colspan ="3"></td>
<td style ="color:red"> {{cash | usd}}</td>
</tr>
</tbody>
</thead>
<tfoot>
<td style ="color:red">Initial Cash</td>
<td colspan ="3"></td>
<td style ="color:red">{{ total_cash | usd }} </td>
</tfoot>
</table>
{% endblock %}
javascript code:
$(document).ready(function () {
// Check if user saw the modal
var key = 'hadModal',
hadModal = localStorage.getItem(key);
// Show the modal only if new user
if (!hadModal) {
$('#myModal').modal('show');
}
// If modal is displayed, store that in localStorage
$('#myModal').on('shown.bs.modal', function () {
localStorage.setItem(key, true);
})
});
The problem with this code is that the modal showed only once and never again. (P.S. I have als tried the cookie approach, which didn't work either) It showed up just for one user and not for the other newly registered one. Any help would be greatly appreciated.
I think you need something like this
$(document).ready(function () {
var users = ['email1', 'email2'] //pushes all logged users here
function checkUsers() { //call this function on every log in
// Check if user saw the modal
var key = 'hadModal',
hadModal = JSON.parse(localStorage.getItem(key));
var loggedUserEmail //
// Show the modal only if new user
if (!hadModal) {
$('#myModal').modal('show');
users.push(loggedUserEmail) // push new user in users
} else {
if (!hadModal.includes(loggedUserEmail)) { // check if logged user is new
$('#myModal').modal('show');
users.push(loggedUserEmail) // push new user in users
}
}
// If modal is displayed, store that in localStorage
$('#myModal').on('shown.bs.modal', function () {
localStorage.setItem(key, JSON.stringify(users));
})
}
});

How to dynamically submit form input values with OnChange event using JQuery in django

I'm currently developing a simple true odd finder calculator using python, django and jquery. I need to have form input submit actions executed by jQuery as the user types in the input values. The goal is to get rid of submit buttons in the frontend html. As of nowadays calculator based web applications don't require submit buttons. The functionality behavior should look like here. I did a research and found out that i need to use JQuery. After implementing the functionality in my app, am able to type the first form input element, however upon clicking the second form input so as to start typing, my application crashes with server error 500, if i go back then type the second form input, it updates output.
How can i implement form input onChange using jquery to match the referenced functionality above.
My template and JQuery code
{% extends "base.html" %}
{% block title %}Two Way True Odd Finder{% endblock %}
{% block content %}
<script type="text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.form-control').change(function () {
$('#myform').submit();
});
});
</script>
<div class="container m-5">
Dashboard Home
3 Way True Odds Finder Calculator
</div>
<div class="container m-5 text-justify">
<div class="row">
<div class="col-4">
<form action="" method="post" id="myform">
{% csrf_token %}
<div class="mb-3">
<label for="Odd1" class="form-label">Odd 1</label>
<input type="number" class="form-control" name="odd1" id="Odd1" min=" " value=" " step=".001" required='required'>
</div>
<div class="mb-3">
<label for="Odd2" class="form-label">Odd 2</label>
<input type="number" class="form-control" name="odd2" id="Odd2" min=" " value=" " step=".001" required='required'>
</div>
<!--<button type="submit" class="btn btn-primary">Submit</button>-->
</form>
</div>
<div class="col-8">
<div class="row">
<div class="col-sm-6">
<div class="card shadow-sm p-3 mb-5 bg-white rounded">
<div class="card-body">
<h5 class="card-title">Results</h5>
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Odd1</th>
<th scope="col">Odd2</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">Initial Odds With Juice</th>
<td>{{HomeOdd}}</td>
<td>{{AwayOdd}}</td>
</tr>
<tr>
<th scope="row">Implied Probability Win %</th>
<td>{{Home_implied_probability}}</td>
<td>{{Away_implied_probability}}</td>
</tr>
<tr>
<th scope="row">True Odds Without Juice</th>
<td class="text-success">{{Home_True_Odd}}</td>
<td class="text-success">{{Away_True_Odd}}</td>
</tr>
</tbody>
</table>
<div class="container text-justify">
<p>Total Implied probability is {{TotalImpliedProbability}}%</p>
<p>Inverted probability is {{Inverted_Probability}}%</p>
<p>Bookie juice is {{Juice}}%</p>
<p>True probability is {{True_Probability}}</p>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="card shadow-sm p-3 mb-5 bg-white rounded">
<div class="card-body">
<h5 class="card-title">Enjoyed the calculator?</h5>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container bg-light p-5">
<h3>HOW IT WORKS</h3>
</div>
</div>
{% endblock %}
django view
def two_way_calc(request):
if request.method == 'POST':
odd1 = float(request.POST.get('odd1'))
odd2 = float(request.POST.get('odd2'))
func_def = odd_finder_true_2(odd1, odd2)
context = {
'Juice': func_def['Juice'],
'TotalImpliedProbability': func_def['TotalImpliedProbability'],
'HomeOdd': func_def['HomeOdd'],
'AwayOdd': func_def['AwayOdd'],
'Home_True_Odd': func_def['Home_True_Odd'],
'Away_True_Odd': func_def['Away_True_Odd'],
'True_Probability': func_def['True_Probability'],
'Home_implied_probability': func_def['Home_implied_probability'],
'Away_implied_probability': func_def['Away_implied_probability'],
'Inverted_Probability': func_def['Inverted_Probability'],
}
return render(request, 'three_way_temp.html', context)
else:
return render(request, 'three_way_temp.html', {})
urls.py
from django.urls import path
from .views import *
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('two_way_calc/', views.two_way_calc, name='two_way_calc'),
]
Python function behind the calculation
def odd_finder_true_2(first_odd, second_odd):
home_implied_probability = round((100/first_odd), 2)
away_implied_probability = round((100/second_odd), 2)
total_implied_probability = home_implied_probability + away_implied_probability
inverted = (100/total_implied_probability) * 100
juice = total_implied_probability - inverted
hundred_odd_home = total_implied_probability/home_implied_probability
hundred_odd_away = total_implied_probability/away_implied_probability
prob_true = 1/(round(hundred_odd_home, 2)) + 1/(round(hundred_odd_away, 2))
my_dict_two = {
'Juice': round(juice, 2),
'TotalImpliedProbability': round(total_implied_probability, 2),
'HomeOdd': first_odd,
'AwayOdd': second_odd,
'Home_True_Odd': round(hundred_odd_home, 2),
'Away_True_Odd': round(hundred_odd_away, 2),
'True_Probability': round(prob_true, 1),
'Home_implied_probability': home_implied_probability,
'Away_implied_probability': away_implied_probability,
'Inverted_Probability': round(inverted, 2)
}
return my_dict_two
so there are a few things that i should say before your answer
First of all it's better approach to use AJAX instead of submit your form because AJAX prevents the page from being reloaded and by using it you do not need to send a whole complete http request and receive a complete response
It will only send needed information to server and get exact answer and js helps you to inject that data in your page
Second you don't actually and necessarily need jQuery, you can do what you want in pure js using fetch API however jQuery is an option too
Now the answer
5xx Errors are server side errors and thank to you for sending your complete code i can show you error
So the problem is when you trigger submit event, you are changing one input and this causes your form to be submitted,
BUT, WHAT ABOUT SECOND INPUT?
it has no value and thus your server can't do the calculations right
How to fix this?
It's up to your algorithm, if you can find a default value to be set on the second input, it can solve the probe
Or
You can check it in you jQuery code
$(".form-control").on("change",function(){
if($("Odd2").value !== "")
$('#myform').submit()
}) ;
Also The jQuery code you've write is correct but it can be better
You are using change event which fires after the value is changed AND when user left the input (blur event)
You will get a better and more live result using input event
$(".form-control").on("input",...)
===============
Updated, based on your last comments, my guess was right and you want the answer to be shown to the user immediately after he entered the number
So you need to use another event called input here's the result (you can add a simple alert before that if to see how input event fires
$(".form-control").on("input",function(){
if($("Odd2").value !== "")
$('#myform').submit()
}) ;
Let me know if your code is changed a lot and provide me your new jQuery code if this didn't solve your problem
============
Updated
Again my guess was right and you need to prevent page from being reloaded (or redirected) this can be done by AJAX
you have multiple choices in AJAX
you can use pure JS (xmlHttpRequest object)
you can use Fetch API in js
you can use Axios.js which is a great library designed to handle Ajax requests and responses
Or finally you can use jQuery
Because in your project you are already using jQuery, I'll do it using jQuery but i don't approve it, Fetch is best option in my opinion, anyway :
$(".form-control").on("input",function(){
if($("Odd2").value !== "")
var fData = new FormData($('#myform'));
var jqxhr = $.ajax({
url: 'AddressToYourBackendFile',
method : 'POST',
data : fData
});
jqxhr.done( res => {
console.log('your response is ready :\n' + res);
});
}) ;

can't refresh the data in a DIV python Django nor the page after a jquery

Let me start by saying I have 2 variables in an HTML template(messages and users) and I have multiple buttons that when one of them is clicked it calls a jquery code that sends a post request to a Django server and it returns an update to a variable(messages)
however, it's not updating the loop, I also tried to return a new HTML page that contains the new variable updated but the jquery is not updating the whole page with the new HTML
if I can update the variable alone it would be better and if I can't do that how can I make jquery use the new HTML page
the python code i used to return the update to the varialbe messages:
if request.method == 'POST':
send=Message.objects.filter(from_id=request.POST.get('userId'),to_id=2)
rec=Message.objects.filter(from_id=2,to_id=request.POST.get('userId'))
messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True)
print(messages)
return HttpResponse(list(messages))
and the code i used to return new HTML template:
m = Message.objects.filter(to_id=2).order_by('-id')
users = {}
for i in m:
if users.get(i.from_id.username) == None:
users[i.from_id.username] = User.objects.get(id=i.from_id.id)
users = list(users.values())
send=Message.objects.filter(from_id=users[0].id,to_id=2)
rec=Message.objects.filter(from_id=2,to_id=users[0].id)
messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True)
if request.method == 'POST':
send=Message.objects.filter(from_id=request.POST.get('userId'),to_id=2)
rec=Message.objects.filter(from_id=2,to_id=request.POST.get('userId'))
messages=sorted(chain(rec, send),key=lambda instance: instance.id,reverse=True)
print(messages)
return render(request,'psych.html',{"users":users, "messages":list(messages)})
return render(request,'psych.html',{"users":users, "messages":list(messages)})
the HTML code and jquery code that uses the variable and try to update it
function newUser(id){
$.ajax({
type: 'POST',
url:'/psych.html/',
data:{
userId:id,
},
success: function(data){
console.log(data);// the data returnd are correct and as needed
//but i cant make it update the messages
$('#messageDiv').load(document.URL + ' #messageDiv');
}
})
}
{% for i in users %}
<li class="">
<button type="button" class="btn" onClick="newUser({{i.id}})">
<div class="d-flex bd-highlight">
<div class="img_cont">
<!-- here was an image ----------------------------------------------->
</div>
<div class="user_info">
<span>{{i.id}}</span>
</div>
</div>
</button>
</li>
{% endfor %}
<!-- The varialbe that i'm trying to update is called messages bottom -->
{% for o in messages %}
{% if o.to_id.id != 2 %}
<div class="d-flex justify-content-start mb-4">
<div class="img_cont_msg">
<!-- here was an image-->
</div>
<div class="msg_cotainer">
{{o.message}}
<!-- <span class="msg_time">{{o.time}}</span> -->
</div>
</div>
{% else %}
<div class="d-flex justify-content-end mb-4">
<div class="msg_cotainer_send">
{{o.message}}
<!-- <span class="msg_time_send">{{o.time}}</span> -->
</div>
<div class="img_cont_msg">
<!-- here was an image-->
</div>
</div>
{% endif %}
{% endfor %}
if it helps i did it before and updated the messages from jquery but i used form and there was only 1 variable i will add the code to that too
$(document).on('submit','#submitMessage', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url:'/psych.html/',
data:{
message:$('#messageHolder').val(),
csrfmiddlewaretoken: $('input[message=csrfmiddlewaretoken]').val(),
},
success: function(data){
// it work like charm here
$('#messageDiv').load(document.URL + ' #messageDiv');
}
})
})
{% for o in messages %}
{% if o.to_id.id == 2 %}
<div class="d-flex justify-content-start mb-4">
<div class="img_cont_msg">
<!-- here was an image-->
</div>
<div class="msg_cotainer">
{{o.message}}
<!-- <span class="msg_time">{{o.time}}</span> -->
</div>
</div>
{% else %}
<div class="d-flex justify-content-end mb-4">
<div class="msg_cotainer_send">
{{o.message}}
<!-- <span class="msg_time_send">{{o.time}}</span> -->
</div>
<div class="img_cont_msg">
<!-- here was an image-->
</div>
</div>
{% endif %}
{% endfor %}
<form id="submitMessage" >
{% csrf_token %}
<div class="card-footer">
<div class="input-group">
<div class="input-group-append"></div>
<input name="message" class="form-control type_msg" placeholder="Type your message..." id="messageHolder">
<div class="input-group-append">
<button type="submit" class="btn">
<span class="input-group-text send_btn" ><i class="fas fa-location-arrow"></i></span>
</button>
</div>
</div>
</div>
</form>
Try this
$("#messageDiv").load(location.href+" #messageDiv>*");
i figured the problem and it was because i didn't know that
$("#messageDiv").load(location.href+" #messageDiv>*");
would make a GET request so all I did was adding the necessary data to the URL and then change the URL too(so if the client refreshed the page it would stay in the same spot) without refreshing the page and then do the command app there
if it could help anyone please look at the code below:
function newUser(id){
var url = document.URL;
url = url.split('/');
url[url.length-2] = id;
url = url.join('/');
window.history.pushState("object or string", "my website name", url);
$('#messageDiv').load(url + ' #messageDiv');
}
sadly i don't know how to do post requst then load the page please if you know comment down bellow so someone else might get help from it

Receive a value from a view to a controller

I have a home view that shows sneakers:
When you put the cursor over a pair of shoes, the card slides down and shows the sizes that exist in the database if they have stock.
I would like to know how I could go about choosing a size so that I can record that value and send it to the controller.
I have done something like this:
<div class="all-sizes">
<div id="stock-size-{{$stock->id}}" class="stock-size" onclick="changeText({{$stock->id}})">
<span>{{$stock->size}}</span>
<input type="hidden" name="size" value="{{$stock->size}}"/>
</div>
</div>
I have tried to pass it through an input type hidden to the controller and there pick it up, but I think I would need an id or something ...
The controller:
public function add($id, Request $request) {
$product = Product::find($id);
$size = $request->input('size');
if ($product) {
$cart_item = new CartItem();
$cart_item->user_id = \Auth::user()->id;
$cart_item->product_id = $product->id;
$cart_item->quantity = 1;
$cart_item->size = $size;
$cart_item->save();
}
return redirect()->route('home')->with(['message', $product->brand." ".$product->name." ".'añadido a la cesta']);
}
(The rest of the code works perfectly, it just fails that $ size picks me up null)
I would also like to know how to make sure that when I press the sizes, I do not change the styles of all of them, (If not, if for example, I press 19 it is colored but if I then press 30 the 19 return to their normal styles and color 30)
Now I have something like this:
The code that colors them and changes the styles:
function changeText(id) {
var stock_size = document.querySelector("#stock-size-" + id);
var stock_size_span = document.querySelector("#stock-size-" + id + " span");
stock_size.style.borderStyle = "none";
stock_size.style.backgroundColor = "black";
stock_size_span.style.color = "white";
}
Thanks!!
EDIT: Updated with all code from view.
<div class="swiper-container">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
#foreach($products_limit as $product)
<div class="swiper-slide">
<div id="card-{{$product->id}}" class="home-card" onmouseenter="mouseEnterMethod('{{$product->id}}')" onmouseleave="mouseLeaveMethod('{{$product->id}}')">
#foreach($product->product_images as $i=>$product_image)
#if($i<1)
<a href="{{route('product.detail', ['brand' => $product->brand, 'name' => $product->name])}}"><img id="image-{{$product->id}}" class="card-image" src="{{url('product/'.$product_image->image)}}">
#endif
#endforeach
<h2>{{$product->brand . " ". str_replace('-', ' ', $product->name)}}</h2>
#if($product->discount>0)
<span><s>{{$product->price}} €</s></span>
<span class='discount'>-{{$product->discount}}%</span>
<p>{{\CountCartItem::calcPriceWithDiscount($product->id)}} €</p>
#else
<span></span>
<p>{{$product->price}} €</p>
</a>
#endif
#if(count($product->stocks)>0)
#foreach($product->stocks->sortBy('size') as $stock)
#if($stock->stock>0)
<div class="all-sizes">
<div id="stock-size-{{$stock->id}}" class="stock-size" onclick="changeText({{$stock->id}})">
<span>{{$stock->size}}</span>
<input style="display:none;" name="size" value="{{$stock->size}}"/>
</div>
</div>
#else
<p class='no-stock'>{{$stock->size}}</p>
#endif
#endforeach
#else
<p>No hay Stock!!</p>
#endif
Add to Cart
</div>
</div>
#endforeach
</div>
<!-- If we need navigation buttons -->
<div class="swiper-button-prev"></div>
<div class="swiper-button-next"></div>
</div>
Please don't make the input type "hidden", instead change it's style to hide is from display like this:
<input type="number" name="size" value="{{$stock->size}}" style="display:none;"/>

my select2 jquery only work for the first form

i want to use select2.min.js to auto-complete the choices (ForeignKey values) , but it only work for my first form , i used django formset for duplicate forms
this is my snippet
<tbody class="tbody tb1 " id="form_set">
{% for item in items.forms %}
<tr class="p-0 col-12">
<td class="">
<div class="col-12 p-0 mt-3 inp">
<input class="col-12 0qarz qarz" type="number" name="" placeholder="qarz">
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.price | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.quantity | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.model | add_class:'col-12 0model model' | attr:'id:model'}}
</div>
</td>
</tr>
{% endfor %}
</tbody>
<script type="text/javascript">
$(function(){
$('.tb1 tr:last').formset({
prefix:'{{items.prefix}}',
addText:'add',
deleteText:'remove',
addCssClass:'btn btn-success',
});
})
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#model").select2()
})
</script>
but the select2 only work for my first form then doesnt have any effect on other forms ! and how to set number of forms to add_class it will help to solve maybe?
thanks
First of all I would love to see a little bit more, for example how you actually define your formset. It is not also clear to me what are you trying to do here. Please paste more data.
I would suggest that you think about using django-select2 module that helps a lot with handling select2 stuff in django.
I am also not sure what you mean by "how to set number of forms", maybe you wish to include some incremental counter that can be done with {{ forloop }} inside for/endfor loop?
Please paste more stuff and answer will be better.
The selector you are using to initialize select2 #model is for element ids, which should be unique for each element in the DOM.
In most browsers the effect will be that only the first instance of an element id will be recognized, and the rest ignored as if they don't exist.
In this instance you want to use a class selector: .model. This will ensure select2 is initialized for all elements that have the class "model". So the code to initialize select2 would be:
<script type="text/javascript">
$(document).ready(function(){
$(".model").select2()
})
</script>
You have to reinitialize(like this way: $("#model").select2();) the select2 for other pages when they appear.
You should need separately initialize with different ids.
for example:
<script type="text/javascript">
$(document).ready(function(){
$("#id_1").select2();
$("#id_2").select2();
})
</script>
the way I found is sending the number of forms through context then apply for loop in the template.
views.py
get_context_data()
context.update({
"accessoryNum": len(StoreRequestAccessory.objects.filter(storeRequestId=self.object.pk)),
"oneDimensionalItemNum":len(StoreRequestOneDimensionalItem.objects.filter(storeRequestId=self.object.pk)),
"twoDimensionalItemNum":len(StoreRequestTwoDimensionalItem.objects.filter(storeRequestId=self.object.pk)),
})
template.html
{% block javascripts %}
<script>
{% comment %} get accessoryNum from context {% endcomment %}
var accessoryNum = {{accessoryNum}};
$(document).ready(function(){
for(let i = 0; i <=accessoryNum; i++){
$(`#id_storereq_accessory_form-${i}-accessoryId`).select2({
placeholder: "Select a Item",
allowClear: true
});
}
});
</script>
{% endblock javascripts %}

Categories

Resources