How I can add thousand separators for number input fields in a ModelForm. I am using 'load humanize' and '|intcomma' in templates to format some numbers.but How I could do that for fields in modelforms.
You can do that by setting USE_THOUSAND_SEPARATOR=True as described here.
Actually I think you should try and handle it on the client side with JS. This was also my solution.
This is how I solved the problem:
create general number format JS function:
function number_format (number, decimals, dec_point, thousands_sep) {
number = (number + '').replace(/[^0-9+-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
}
create thousand separator specific code:
function thousand_sep(tagID, x_value) {
if (x_value == "") {
document.getElementById(tagID).value = "";
return;
}
document.getElementById(tagID).value = number_format(x_value, 0, ',', ' ');
}
Add the code to your ModelForm in your Django forms.py:
class AnyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(AnyForm, self).__init__(*args, **kwargs)
self.fields['numeric_field'].widget.attrs = {
'oninput': "thousand_sep(this.id, this.value)",
}
This works for me. Hope it helps. (sorry for the JS code format, it did not highlight it as code for some reason)
Related
Would be grateful if any ideas to speed it up!
case class Pair(aa:String, bb:String)
case class OutputRow(bb:String, aa:String, bb_2:String, aa_2:String)
def startSearch(
_1_sorted: Array[Pair] ,
_2_hashmap: HashMap[String, String] ) : ArrayBuffer[OutputRow] = {
var outputTableListBuffer = ArrayBuffer[OutputRow]()
var searchComparisionFlag = false
var storeMain = Pair("0","0") //Initialize with Dummy data
var i = 0
def search(xxxx_1: Pair): Unit = {
if (searchComparisionFlag==true) {
var _2_exists = _2_hashmap.exists(_._1 == xxxx_1.aa)
if (_2_exists) {
val _2_xxxx = _2_hashmap(xxxx_1.aa)
outputTableListBuffer.append(OutputRow(storeMain.aa, storeMain.bb,_2_xxxx, xxxx_1.aa))
i = i + 1
if (i % 1000 == 0) println("In recursive search storeMain: ", storeMain)
var storePair = Pair(_2_xxxx,xxxx_1.aa)
search(storePair)
} else {
searchComparisionFlag = false
return
}
} else {
var _2_exists = _2_hashmap.exists(_._1 == xxxx_1.aa)
if (_2_exists) {
val _2_xxxx = _2_hashmap(xxxx_1.aa)
searchComparisionFlag = true
outputTableListBuffer.append(OutputRow(xxxx_1.aa, xxxx_1.bb,_2_xxxx, xxxx_1.aa))
var store = Pair(_2_xxxx,xxxx_1.aa)
search(store)
}
}
}
_1_sorted.foreach{ aa_1 =>
val store = Pair(aa_1.aa, aa_1.bb)
storeMain = store
search(store)
}
outputTableListBuffer
}
The above function takes 2 hours with 1 million values in _1_sorted and with a good 1 Million lookup in the hashmap.
Any ideas to speed this up?
This is a recursive logic function
The biggest problem is this:
_2_hashmap.exists(_._1 == xxxx_1.aa)
This is checking every single element of the hashmap on every call. Instead, use get:
_2_hashmap.get(xxxx_1.aa) match {
Some(_2_xxxx) => // Found
???
None => // Not found
???
}
Other code issues:
Don't use return
Pass flags down through recursive call rather than using global var
Use val wherever possible
Don't start variable names with _
Problem: How to retrieve from a list and append to a new list saved locally, to be used by methods in the same class.
I would like to store whats in exerciseList and put it into the local variable
List CustomExercises; When I return custom exercises from getAllExercisesAsStrings() it doesn't update.
class GenerateCustom extends ExerciseListState {
int rnd;
GenerateCustom({this.difficulty});
final int difficulty;
String workout;
String ex1;
String ex2;
String ex3;
String ex4;
String ex5;
List customExercises = [];
//get list of custom workouts
List getAllExercisesAsStrings(customExercises) {
var n;
for (n = 0; n < exerciseList.length; n++) {
// print(exerciseList[n].title);
customExercises.add(exerciseList[n].title);
}
return customExercises;
}
For context the getCustomType() gets a random exercise from the list to be displayed.
String getCustomType() {
var random = Random();
var i = random.nextInt(customExercises.length);
print(customExercises[i]);
return customExercises[i];
}
String cExerciseOne() {
if (difficulty == 1) {
workout =
('1: ' + getCustomType() + ' ' + getRepsEasy() + 'x' + getSetsEasy());
} else if (difficulty == 2) {
workout = ('1: ' +
getCustomType() +
' ' +
getRepsMedium() +
'x' +
getSetsMedium());
} else {
workout =
('1: ' + getCustomType() + ' ' + getRepsHard() + 'x' + getSetsHard());
}
return workout;
}
When I print to console exerciseList[n].title it returns the list with the exercises e.g. ['exercise1','Bicep Curl', 'Pull Up', ] etc. These exercises have already been retrieved in the parent class and I would like to store them in the new list. Any guidance would be great and if you think more context is needed let me know.
The reason why List customExercises isn't populated is because customExercises.add() is being called inside a Stateful Widget. To add new Objects to the List, you'd need to call setState() when an item is added.
setState(() {
customExercises.add(exerciseList[n].title);
});
I'm need of help parsing a custom file structured file. As you can see below is the structure. The issue is that I can't seem to parse the structure correctly, namely myOriginalFormula & myBonusType in the same group when I want them seperated for example.
AttributeDictionary SomeDictName
{
myAttributeDefinitionCategories
{
AttributeDefinitionList SomeList
{
AttributeDefinition SomeDefinitioName < uid=8972789HHDUAI7 >
{
myOriginalFormula "(A_Variable) * 10"
myBonusType FlatValue
}
AttributeDefinition UIBlankAttribute < uid=JIAIODJ7899 >
{
}
AttributeDefinition SomeOtherDefinitionName < uid=17837HHJAJ7788 >
{
myOriginalFormula 1
mySpecializations
{
Specialization "Some_Specialization 1"
{
myCondition "Something.MustEqual = 1"
myFormula 0
}
Specialization "SomeSpecialization 2"
{
myCondition "Something.MustEqual = 2"
myFormula 0.026
}
}
myBonusType FlatValue
}
AttributeDefinition SomeReal_Other_definition < uid=6768GYAG//() >
{
myOriginalFormula "(Some_Formula / Other_Variable) - 1"
myBonusType Percentage
myUINumDecimals 1
myHasAddSignUI FALSE
}
}
}
}
My try is blow. Could someone help me parse this structure correctly?
def syntaxParser():
# constants
left_bracket = Literal("{").suppress()
right_bracket = Literal("}").suppress()
semicolon = Literal(";").suppress()
space = White().suppress()
key = Word(alphanums + '_/"')
value = CharsNotIn("{};,")
# rules
assignment = Group(key + Optional(space + value))
block = Forward()
specialblock = Forward()
subblock = ZeroOrMore(Group(assignment) | specialblock)
specialblock = (
Keyword("Specialization")
+ key
+ left_bracket
+ subblock
+ right_bracket)
block << Group(
Optional(Group(key + Optional(space + value)))
+ left_bracket
+ Group(ZeroOrMore(assignment | Group(block) | Group(specialblock)))
+ right_bracket)
script = block
return script
Your definition of value is too greedy:
value = CharsNotIn("{};,")
I don't know how this works with the format you are parsing, but I get better results with this:
value = quotedString | CharsNotIn("{};,\n")
I want to create a dropdown menu With English or German as the options in Javascript / jQuery that checks that:
check if on a domain - say happy.com/pizza
if german is selected on dropdown
redirect user to
happy.de/pizza
and I could have a list
if happy.com/pizza got to happy.de/pizza
happy.com/coke got to happy.de/coke
happy.com/juice got to happy.de/juice
etc etc.
I have written the code yet but how would one go about this?
Thanks!
I have written some code but I just need a little help please:
In this scenario I am on the www.something.com/beer page and want it to go to the German Beer Page!
<select>
<option value="1">English</option>
<option value="2">German</option>
</select>
if(value == 2) && is current domain www.something.com/beer{
window.top.location.href = 'www.something.de/beer';
}else if(value == 2) && is current domain www.something.com/cheese{
window.top.location.href = 'www.something.de/cheese';
}else{
do nothing
}
How do I get this to check the value of the dropdown and the domain is currently on?
Here is my Jsfiddle
http://jsfiddle.net/msasz2an/
Thanks again!
function current(arr) {
// discuss at: http://phpjs.org/functions/current/
// original by: Brett Zamir (http://brett-zamir.me)
// note: Uses global: php_js to store the array pointer
// example 1: transport = ['foot', 'bike', 'car', 'plane'];
// example 1: current(transport);
// returns 1: 'foot'
this.php_js = this.php_js || {};
this.php_js.pointers = this.php_js.pointers || [];
var indexOf = function (value) {
for (var i = 0, length = this.length; i < length; i++) {
if (this[i] === value) {
return i;
}
}
return -1;
};
// END REDUNDANT
var pointers = this.php_js.pointers;
if (!pointers.indexOf) {
pointers.indexOf = indexOf;
}
if (pointers.indexOf(arr) === -1) {
pointers.push(arr, 0);
}
var arrpos = pointers.indexOf(arr);
var cursor = pointers[arrpos + 1];
if (Object.prototype.toString.call(arr) === '[object Array]') {
return arr[cursor] || false;
}
var ct = 0;
for (var k in arr) {
if (ct === cursor) {
return arr[k];
}
ct++;
}
// Empty
return false;
}
I am trying to extend dijit.form.FilteringSelect with the requirement that all instances of it should match input regardless of where the characters are in the inputted text, and should also ignore whitespace and punctuation (mainly periods and dashes).
For example if an option is "J.P. Morgan" I would want to be able to select that option after typing "JP" or "P Morgan".
Now I know that the part about matching anywhere in the string can be accomplished by passing in queryExpr: "*${0}*" when creating the instance.
What I haven't figured out is how to make it ignore whitespace, periods, and dashes. I have an example of where I'm at here - http://jsfiddle.net/mNYw2/2/. Any help would be appreciated.
the thing to master in this case is the store fetch querystrings.. It will call a function in the attached store to pull out any matching items, so if you have a value entered in the autofilling inputfield, it will eventually end up similar to this in the code:
var query = { this.searchAttr: this.get("value") }; // this is not entirely accurate
this._fetchHandle = this.store.query(query, options);
this._fetchHandle.then( showResultsFunction );
So, when you define select, override the _setStoreAttr to make changes in the store query api
dojo.declare('CustomFilteringSelect', [FilteringSelect], {
constructor: function() {
//???
},
_setStoreAttr: function(store) {
this.inherited(arguments); // allow for comboboxmixin to modify it
// above line eventually calls this._set("store", store);
// so now, 'this' has 'store' set allready
// override here
this.store.query = function(query, options) {
// note that some (Memory) stores has no 'fetch' wrapper
};
}
});
EDIT: override queryEngine function as opposed to query function
Take a look at the file SimpleQueryEngine.js under dojo/store/util. This is essentially what filters the received Array items on the given String query from the FilteringSelect. Ok, it goes like this:
var MyEngine = function(query, options) {
// create our matching query function
switch(typeof query){
default:
throw new Error("Can not query with a " + typeof query);
case "object": case "undefined":
var queryObject = query;
query = function(object){
for(var key in queryObject){
var required = queryObject[key];
if(required && required.test){
if(!required.test(object[key])){
return false;
}
}else if(required != object[key]){
return false;
}
}
return true;
};
break;
case "string":
/// HERE is most likely where you can play with the reqexp matcher.
// named query
if(!this[query]){
throw new Error("No filter function " + query + " was found in store");
}
query = this[query];
// fall through
case "function":
// fall through
}
function execute(array){
// execute the whole query, first we filter
var results = arrayUtil.filter(array, query);
// next we sort
if(options && options.sort){
results.sort(function(a, b){
for(var sort, i=0; sort = options.sort[i]; i++){
var aValue = a[sort.attribute];
var bValue = b[sort.attribute];
if (aValue != bValue) {
return !!sort.descending == aValue > bValue ? -1 : 1;
}
}
return 0;
});
}
// now we paginate
if(options && (options.start || options.count)){
var total = results.length;
results = results.slice(options.start || 0, (options.start || 0) + (options.count || Infinity));
results.total = total;
}
return results;
}
execute.matches = query;
return execute;
};
new Store( { queryEngine: MyEngine });
when execute.matches is set on bottom of this function, what happens is, that the string gets called on each item. Each item has a property - Select.searchAttr - which is tested by RegExp like so: new RegExp(query).test(item[searchAttr]); or maybe a bit simpler to understand; item[searchAttr].matches(query);
I have no testing environment, but locate the inline comment above and start using console.debug..
Example:
Stpre.data = [
{ id:'WS', name: 'Will F. Smith' },
{ id:'RD', name:'Robert O. Dinero' },
{ id:'CP', name:'Cle O. Patra' }
];
Select.searchAttr = "name";
Select.value = "Robert Din"; // keyup->autocomplete->query
Select.query will become Select.queryExp.replace("${0]", Select.value), in your simple queryExp case, 'Robert Din'.. This will get fuzzy and it would be up to you to fill in the regular expression, here's something to start with
query = query.substr(1,query.length-2); // '*' be gone
var words = query.split(" ");
var exp = "";
dojo.forEach(words, function(word, idx) {
// check if last word
var nextWord = words[idx+1] ? words[idx+1] : null;
// postfix 'match-all-but-first-letter-of-nextWord'
exp += word + (nextWord ? "[^" + nextWord[0] + "]*" : "");
});
// exp should now be "Robert[^D]*Din";
// put back '*'
query = '*' + exp + '*';