How to access itertools object in django - javascript

I have defined a get_queryset() method where i want to return two queryset objects like:
get_queryset(self):
r1 = Books.objects.filter(auther_id=1);
r2 = Books.objects.filter(~Q(auther_id=1));
return r1,r2
The call to this method comes from a javascript file with an ajax call.
Now i want to access r1 and r2 individually in the js file.
I tried doing
r=chain(r1,r2) // in views.py
r.r1.fieldName and r.r2.fieldName // in js file.
I am unsure how could i unchain the itertools object. If it is not possible can anyone tell me about some other approach for this.
I also see method like ifilter() and etc to access the object but i want to access it in js.
EDIT: I have edited the code . CAN i club both query like
Books.objects.all()
and in the js do something to get two lists one having books by auther_id 1 and second list having other auther ids.

This doesn't make any sense at all. You can't 'unchain' something; the whole point of chain is that it makes the individual elements into one single undifferentiated item, there is no way of telling where one of the originals ended and the next started.
If you want to access two querysets individually in the template, then pass two individual querysets.

Related

Merging arrays defined on different pages using concat

I have two arrays I want to merge them into one.
let signUps = [];
let usersInputs = [];
but each of them has been defined on different pages and therefore when I try
function mergeArray (){
var merged = signUps.concat(usersInputs);
document.getElementById('btn').innerHTML = merged
console.warn('added' , [merged] );
}
It says, on this occasion, usersInputs is not defined.
I have encountered this problem on so many occasion, maybe my lack of understanding. so how one approaches this problem?
On different pages you mean it's completely on a separate HTML document and you want to merge them together? In a web page whatever JavaScript you execute is available only inside of that webpage, not on a separate one.
You may either want to store your data on server, or pass it using form data, or best make use of localStorage or sessionStorage API in JavaScript to pass data from one page to another in a simple way.

Preventing a section of html from referring to other tags / elements on the same page

I have a php webpage that includes some graphical dials created with css and javascript (and an ajax call). Each dial is added to the webpage using:
$_SESSION['info'] = dial1 Specific info.
include 'dial.php';
$_SESSION['info'] = dial2 Specific info.
include 'dial.php';
Inside dial.php, there is a section that analyzes the SESSION variable to adjust an arm on the dial, and creates the dials circular shape with css. The problem I'm trying to solve is the second dial is a copy of the first dial, and not distinct.
How can I make the above code force each "include 'dial.php'" to operate independently from each other and not interact with each other (since the variables, function names, and css names are the same for each dial).
Best Regards
you can not add two different object into one variable !
make your session variable as an array like below :
$_SESSION['info'][1] = dial1 Specific info.
include 'dial.php';
$_SESSION['info'][2] = dial2 Specific info.
include 'dial.php';
for a better answer , put your dial.php code , I'll update my answer
The session variable can hold many types of data but you need to structure the session variable in a different manner to your initial code. If you were to assign an object as the value ( as below ) you can access the right piece of information easily using the object notation shown below.
$_SESSION['info']=(object)array(
'dial_1' => 'dial1 Specific info',
'dial_2' => 'dial2 Specific info'
);
then access the individual info by
$info=$_SESSION['info']->dial_1;
So I ended up using dynamic html tag ids, function names, and variables. It seems to be working out fine.

How to convert javascript array to scala List object

I have inherited some code that uses the Play! framework which has scala.html files that have javascript in them. Play! and scala are all new to me.
One of the javascript functions does a post and gets back a JSON object. It then loops through the JSON object and creates an array.
var myArray = [];
function createArray(){
$.post('/createArray', $('#arrayForm').serialize()).done(function( data ) {
var obj1 = JSON.parse(data);
$.each(obj1, function(idx, obj) {
myArray.push(obj.name);
});
});
return true;
}
It then uses this array (of strings) to create a text input field that does autocomplete using the data in the array.
I want/need to convert this text input to a select dropdown using the Play! #select but the options arg for #select wants a List object (or Map or Seq - just figured List would be easier since I already have an array of strings).
If I manually create the List object, it works fine.
#select(pForm("equipName"), options(scala.collection.immutable.List("Yes","No")))
The problem is I cannot figure out how to convert the myArray array to a List object which I can then pass to the #select options.
I have found a lot of posts that talk about converting a scala List to an array but can't find a way to go the other way. I am hoping it is an easy thing that I can't seem to figure out.
Thanks in advance for the help.
You can not do that. And more precisely - you do not want to do that.
So basically your play application run on server. In your Play application all those .scala html files are compiled to generate some functions.
Now, when a play application receives a request from a client browser, it gets mapped to some controller by by router. The controller does some processing and finally take one of these above functions ( lets say for index.scala.html we get views.html.index ) and call this function with some parameters.
These functions returns some text which is then sent to the client's browser as HTTP response with response header Content-Type:text/html; charset=utf-8 which tells the browser to treat this text as html.
Now, the browser renders the html which has embedded JavaScript and hence runs the JavaScript. So... basically your JavaScrpt code does not exist on server... for play all of it is just text.
Both of these Scala code and JavaScript code are executed at very different times, at different computers and in different environments hence you can not do whatever you are saying.

Return the result of a method in a QuerySet.values() or values_list()?

When calling .values() or .values_list() on a QuerySet you can pass in the specific fields you want returned, or even fields you want from related tables. What I'm wanting to do is include the result of a method defined on the model, in addition to some fields, for example:
class MyModel(models.Model):
name = models.CharField()
def favouriteNumber(self):
return random.randint(1,10)
list(MyModel.objects.all().values('name','favouriteNumber'))
=> [{'name':'Bob', 'favouriteNumber':6}, {'name':'Fred', 'favouriteNumber':4}]
The above doesn't work, but is what I'm wanting to do, in the same way that the templating language can treat model methods without parameters just like fields.
The reason I'm wanting to do this is so that I can pass the information to the JavaScript in the front end to use instead of making calls back to the server to retrieve it each time.
Assuming the above (or something similar) isn't possible, I know I could loop over my values() result afterwards and add in the extra information manually.. what would be the most efficient (and clean) way to do that?
You might want to try using only() instead of values(). Like values() it will only fetch the specified fields from the database, but unlike values() it will return actual instance objects that you can call methods on.
That way, whether you're looping in the view or the template, you can access the method in addition to the specified fields.
If you need dictionary-like structures (for json.dumps(), say) you can just construct them in a comprehension:
instances = MyModel.objects.only('name')
data = [{'name': instance.name,
'favourite': instance.favouriteNumber()} for instance in instances]

jQuery Id Selection and Dynamic Arrays

I have some code I'm struggling with. The good news is the code working as intended for a single instance; after some thought I've decided to feature multiple of these image selectors on a page. This works but the ugly approach of duplicating the code doesn't scale well (e.g. what if you want 50 of these on there?) The snag I've hit is how I can refer to a specific array. Is an array even an ideal solution for this?
The Objective
I have a series of images that a user may select from, up to X amount. The selected image ids are stored in an array and the image is added to a "selected images pool". This occurs by using an onClick for the slider, I obtain the Id from the element attributes. This is where I'm getting stuck.
var dataArray = $(this).closest("[id^=carousel]").data('array');
var slideCounter = $(this).closest("[id^=carousel]").data('counter');
slideCounter = dataArray.length;
The slideCounter returns the length of the string, not the array elements. How can I tell this code to refer to a particular array? See the fiddle for a better idea of the markup and code: jsFiddle
I have no doubt that there is a better approach. I'm relatively new to front end work, I'd appreciate any insights, I've burnt some brain cells on this, thanks!
From looking at your HTML, it looks like when you do this:
var dataArray = $(this).closest("[id^=carousel]").data('array');
what you're trying to do is to read the name of an array with .data() and then somehow turn that name (which is a string) into the array that's in your variable. My guess is that there's probably a better way to structure your code rather than putting javascript variable names in your HTML. I'd probably put a key name in the HTML and then store the arrays in an object where you can access them by that key name at any time.
Without trying to refactor your code, here's an idea for what you were trying to accomplish:
If selectedSlidesIdArray1 is a global variable, then you can do this:
var dataArray = window[$(this).closest("[id^=carousel]").data('array')];
Using the [stringVariable] notation on an object, lets you access a property by a literal string or a variable that contains a string. Since all global variables are also properties on the window object, you can do it this way for global variables.
If selectedSlidesIdArray1 is not a global variable, then you should probably put it in an object and then you can do this:
var dataArray = yourObj[$(this).closest("[id^=carousel]").data('array')];
Instead of trying to translate an arbitrary string into a JavaScript variable of the same name, why not just use another array? You can have nested arrays, which is to say an array of arrays.
Thus, instead of selectedSlidesIdArray1, selectedSlidesIdArray2, etc., you would have one selectedSlidesIdArray with sub-arrays, which you could then pull the index for using a data attribute.

Categories

Resources