Learning Django with tutorial and have error.
File "F:\Python\COTSW\teashop\main\views.py", line 98, in cart_list total_amt+=int(item['qty'])*float(item['price'])
ValueError: could not convert string to float: ''
Views.py
def cart_list(request):
total_amt = 0
for p_id, item in request.session['cartdata'].items():
total_amt+=int(item['qty'])*float(item['price'])
return render(request, 'cart.html', {'cart_data': request.session['cartdata'], 'totalitems': len(request.session['cartdata']), 'total_amt': total_amt})
product.html
<div class="col-md-8">
<p>{{data.detail}}</p>
<hr/>
<table class="table table-bordered">
<tr>
<h6>Цена</h6>
<h6>₽ <span class="product-price-{{data.id}}">{{data.price}}</span></h6>
</tr>
</table>
<hr/>
<div class="input-group my-3" style="width:30%;">
<input type="number" value="1" class="form-control product-qty-{{data.id}}" id="productQty" />
<div class="input-group-append">
<input type="hidden" class="product-id-{{data.id}}" value="{{data.id}}" />
<input type="hidden" class="product-title-{{data.id}}" value="{{data.title}}" />
<input type="hidden" class="product-image-{{data.id}}" value="{{data.image}}" />
<input type="hidden" class="product-price-{{data.id}}" value="{{data.price}}" />
<button class="btn btn-primary btn-sm add-to-cart" data-index="{{data.id}}" type="button" id="addToCartBtn"><i class="fa fa-shopping-cart"></i> В корзину</button>
</div>
</div>
</div>
Custom.js
$(document).on('click', ".add-to-cart", function(){
var _vm=$(this);
var _index=_vm.attr('data-index');
var _qty = $(".product-qty-"+_index).val();
var _productId = $(".product-id-"+_index).val();
var _productTitle = $(".product-title-"+_index).val();
var _productImage = $(".product-image-"+_index).val();
var _productPrice = $(".product-price-"+_index).text();
var _productSlug = $(".product-slug-"+_index).val();
console.log(_productPrice)
// Ajax
$.ajax({
url:'/add-to-cart',
data:{
'qty':_qty,
'id':_productId,
'title':_productTitle,
'image':_productImage,
'price':_productPrice,
'slug':_productSlug,
},
dataType:'json',
beforeSend:function(){
_vm.attr('disabled', true);
},
success:function(res){
$(".cart-list").text(res.totalitems);
_vm.attr('disabled',false);
}
});
Before changes var _productPrice = $(".product-price").text(); was var _productPrice = $(".product-price").text(); and worked. Console.log showing correct price 500.00, but total_amt+=int(item['qty'])*float(item['price']) taking an empty string.
Everything works correctly in the tutorial and I don't understand what could be wrong.
It seems that item["price"] is an empty string, also the problem maybe that value is not coming to the server from javascript, you can check it whether it's a empty string or not as:
def cart_list(request):
total_amt = 0
for p_id, item in request.session['cartdata'].items():
qty = int(item['qty'])
price = item['price']
if price:
price = float(price)
total_amt += qty * price
else:
# Handle empty price value (e.g. display an error message)
pass
return render(request, 'cart.html', {'cart_data': request.session['cartdata'], 'totalitems': len(request.session['cartdata']), 'total_amt': total_amt})
Try checking this, if its an empty string then some problem with javascript code i.e. numeric value of price is not coming to the server.
You should change the jQuery to read the value of the hidden input field and not “text”.
var _productPrice = $(".product-price-"+_index).text();
should be
var _productPrice = $(".product-price-"+_index).val();
I tried coding this from scratch for the third time and it gave the same error again. I clicked something, cleared cookies and cache, tried to change the code, nothing helped. And suddenly everything worked, the code is the same, I compared it. I don't understand why it didn't work and why it's working now, but Thanks to everyone who tried to help.
Related
I am using summernote rich text editor, and I want to edit my posted data(stored in DB). I am sending the value to the text area and inputs but not showing into the text area and showing into the input. kindly share some solutions and suggestions with me. any jquery and js function like this...
here is rendered data to web page
route.get('/edit/:id', async (req, res) =>{
const id = req.params.id
const article = await Article.findById(id)
res.render('editarticle',{article:article})
})
and here is ejs or HTML
<%- include('header'); -%>
<div class="container-9">
<h2>Create Article Here</h2>
<hr>
<form action="/create/blog" method='post'>
<input type="text" name="title" id="" placeholder="Enter Title" value='<%=article.title%>'/>
<input type="text" name="description" id="dics" placeholder="Enter Description" value='<%=article.discription%>'/>
<hr>
<button id='btn-post' type="submit">Post</button>
<textarea name='content' id="body" rows="10" value="<%=article.content%>" ></textarea>
</form>
</div>
<%- include('footer'); -%>
I have solved this problem with help of one line of code. I have got the solution after 2 month
var value = $('#value').val()
console.log(value);
$('textarea#body').summernote('pasteHTML', value);
if want to render the HTML for edit this will work, var value = $('#value').val() it just receiving the value (HTML) from the backend and $('textarea#body').summernote('pasteHTML', value); this line of code pesting the HTML into summernote editor.
#tushar Very useful !!
I use it on summer note as like
Put Content in a div, and set it display none
<div id="contentDumpDiv" style="display:none;">
<?php echo $post['content'] ?>
</div>
then use this javascript code
var value = $('#contentDumpDiv').html();
$('textarea#saContent').summernote('pasteHTML', value);
I am building a search bar which I want to be disabled unless the user enters something. Appreciate any help to make this work.
This is my handlebars code:
<div class="searchWrapper">
<form action="/founduser" method="POST" class="searchBar">
<input type="hidden" id="groupid" name="groupid" value={{this.groupid}}>
<input type="text" name="searchBar" id="searchBar" placeholder="Enter the user's email ID"
value="{{this.term}}" />
{{!-- <i class="fas fa-search"></i>
<input type="submit" value="" id="submit"> --}}
<button type="submit" class="btn-search" id="user-search-btn"><span class="icon search"
disabled></span></button>
</form>
</div>
and I am running a JS check to alternate
const searchButton = document.getElementById('user-search-btn');
const check = () => {
if (searchButton !== "") {
searchButton.disabled = false
} else {
searchButton.disabled = true
}
}
searchButton.onkeyup = check
Where am I going wrong?
Sorry, I figured where I was going wrong. In my code I was checking if searchButton was empty, however what I should have done was to check the value inside the <input type="text" name="searchBar" id="searchBar" placeholder="Enter the user's email ID" value="{{this.term}}" />.
How do I get the selected result of a search field of Semantic-UI?
Using onSelect event, I can get the selected result, but this does not work when clean the field with the backspace.
Using field.search('get result') also not return the result blank as expected.
You can get the selected result like this:
onSelect:function(result){
console.log(result)
}
Having a sample HTML form with 2 inputs like this (one hidden):
<form id="search-box-form">
<input type="hidden" name="search" value="" />
<div class="ui search location-search">
<div class="ui icon input">
<input class="prompt" type="text" placeholder="Search locations..." />
<i class="search icon"></i>
</div>
<div class="results"></div>
</div>
</form>
The same way you use onSelect to populate your hidden field, you can use onResultsClose to clear your hidden input. Caveat: onResultsClose will run before semantic puts the value on it's own field, hence the need to use timeout function.
jQuery(document).ready(
function() {
jQuery('.location-search')
.search({
source : content,
searchOnFocus : true,
minCharacters : 0,
onSelect: function(result, response) {
var value = result.value;
$('#search-box-form').find('input[name=search]').val(value);
},
onResultsClose: function(){
setTimeout(function() {
if (jQuery('.location-search').search('get value') == '') {
$('#search-box-form').find('input[name=search]').val('');
}
}, 500);
}
})
;
}
);
i have made this simple app with gmaps.js but i need the search functions like they show it here:
http://hpneo.github.io/gmaps/examples/geocoding.html
i looked at the source code and all but it aint working.. The search button reloads the page...
my code is a follows:
<script>
$('#geocoding_form').submit(function(e){
e.preventDefault();
GMaps.geocode({
address: $('#address').val().trim(),
callback: function(results, status){
if(status=='OK'){
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
}
}
});
});
</script>
<form method="post" id="geocoding_form">
<label for="address">Address:</label>
<div class="input">
<input type="text" id="address" name="address" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="map"></div>
the rest is loaded in from scripts.js you can see it in sourcecode. Why is this happening and how can i fix this?
The web app is located here, http://travelers.work/trein/
You need to change
map.setCenter(latlng.lat(), latlng.lng());
to
map.setCenter(latlng);
because the search returns a LatLng object as a result, and that's what is needed as an input for setCenter.
Here's a JS demo with your code: http://jsfiddle.net/DuRhR/3/
EDIT after comments:
Alternatively, you can pass to setCenter a LatLngLiteral
map.setCenter({lat: latlng.lat(), lng: latlng.lng()});
I have 2 versions of my code, one is not working and the other it is.
My question is "why the not working one is not working?"
here is the JSfiddle http://jsfiddle.net/fhjF7/
The not working version:
Controller:
function Ctrl($scope) {
$scope.username = "username";
$scope.users = [ "Matteo", "Marco", "Michele" ];
};
HTML:
<h1> Not working example</h1>
<div ng-controller="Ctrl">
<div ng-repeat="user in users">
<input type="radio" ng-model="username" name="usern" ng-value="user" />
<strong>{{user}}</strong>
</div>
<div>selected: {{username}}</div>
</div>
and here is the working one, which is almost identical but replacing the string variable with an object:
Controller:
function usersCtrl($scope) {
$scope.names = {username: "username"};
$scope.users = [ "Matteo", "Marco", "Michele" ];
};
HTML:
<h1> Working example</h1>
<div ng-controller="usersCtrl">
<div ng-repeat="user in users">
<input type="radio" ng-model="names.username" name="username" ng-value="user" />
<strong>{{user}}</strong>
</div>
<div>selected: {{names.username}}</div>
</div>
It is because of the way javascript manages function parameters.
The easy way to understand it is that String, Number, and Boolean parameters are always sent byValue, while Objects and Functions are always sent byRef, that is why when you use the dot inside an ng-model it means you are doing a reference to an object which will propagate, while if you don't use a dot inside the ng-model, you are referencing a String, Number or Boolean which is actually a copy of the real variable.
More information here https://egghead.io/lessons/angularjs-the-dot and https://github.com/angular/angular.js/wiki/Understanding-Scopes
Ng-repeats create their own isolate scopes, so that's why the string is not being preserved as it's not pass by reference. If you want to update the model use
<input type="radio" ng-model="$parent.username" name="usern" ng-value="user" />
$parent gives you access to the parents scope which is outside the ng-repeat and should be the one you want.
The answer for your not working code : http://jsfiddle.net/ashuslove/fhjF7/30/
HTML :
<h1> Not working example</h1>
<div ng-controller="Ctrl">
<div ng-repeat="user in users">
<input type="radio" ng-model="names.usern" name="usern" ng-value="user" />
<strong>{{user}}</strong>
</div>
<div>selected: {{names.usern}}</div> //Changed line here
</div>
The function :
function Ctrl($scope) {
$scope.names = {usern: "usern"}; //Also need to change this
$scope.users = [ "Matteo", "Marco", "Michele" ];
};