Im building my first Django app.
I want to call a javascript function that receives a list of strings.
In my current version Im sending a Django object (called provider) property like this and it´s working fine:
<i class="fi-download"></i>
But now I want to call a Provider model method that returns a list of strings, so then I can do something with this list in Js method
def get_provider_files_urls(self):
provider_files = self.provider_files.all()
file_list = []
for f in provider_files:
file_list.append(f.file.name)
return file_list
I tried this:
<i class="fi-download"></i>
and got this error:
Uncaught SyntaxError: missing ) after argument list
A quick and dirty way to generate a JS array from a list is to use the join filter
onclick="download_provider_files(['{{ provider.get_provider_files_urls|join:"', '" }}'])"
Probably cleaner to use the json_script filter though
Related
How do I get access to this array, inside it has objects, I used laravel, inertiajs, vuejs, Im passing the variable from laravel controller to vuejs component with inertia.js
public function index($slug,Category $categories)
{
$category = $categories->where('slug',$slug)->with('product')->get();
return Inertia::render('Category',[
'categories' => $category
]);
}
If I understand your point correctly , I think you would like to access the products , then it's better to return from the controller to vue only the products.
and according to the variable naming I think you are expecting only one category to be returned then may be you need to check retrieving single model using ->first()
https://laravel.com/docs/8.x/eloquent#retrieving-single-models
You can loop with v-for or access directly:
categories[0].description
Ive looked related posts and couldn't quite find what I was looking for.
So I am build a backend rest api and I have certain tests I am collecting data on. The tests have their own models, and these models are associated with collections (obviously).
So I have a separate controller for each model. Now I have a "job" controller which queries data from each separate test. Now I have a separate script where I store these model objects in an JSON object. I am wondering how I can access these models properly (I am close but cant quite assign properly). Here is the block:
const testMappings = {
'aprobe':aprobe,
'status':status,
//'rxserial':rxserial,
}
Now when I try assignment as follows, where testMappings is the imported script variable:
const testMappings = activeTests.testMappings;
console.log(testMappings['aprobe']);
I get the following output:
Model {aprobe}
I would like to access the actual aprobe object. Also if anyone knows a better way of dynamically assigning these (instead of having bunch of if statements ie if(name == 'aprobe').... do something), it would be much appreciated.
You are probably looking for something like below :
const name = 'aprobe';
Object.keys(testMappings).indexOf(name) > -1 ? testMappings[name] : null
the above should give you: Model {aprobe}
So basically if the key exists in your object then you'd like to fetch the value of that key which would give you your model dynamically.
I want to serialize my Sounds model for use in my game.js file. This is what I have.
views.py
def index(request):
context = {'sounds': serializers.serialize('json', Sounds.objects.all()) }
return render(request, 'index.html', context)
index.html
<button type="submit" onclick="main()">Let's Start!</button>
game.js
function main(){
var data = {{ context|safe }};
// print all objects here
}
It's not working - not sure what the issue is. Basically, when I click the button in index.html, it should go to the main function (this part works), and then set a variable data with the objects in the model so that I can use it. Also, is it possible to filter objects in data so that I have a list with only the objects with id = 1? I want to do this in game.js (not in views.py or elsewhere).
It's hard to tell what the exact problem with the serialiser is without an actual error log. If you can actually open the console that django is running in, it should display the error when it occurs. From that a better diagnostic of the issue can be made. It would be wise to do this in the future otherwise questions like this will be downvoted.
Yes, you can filter arrays in Javascript using the filter function. The function creates a new array by interating through the objects in the array that will be passed into a function, which should return true if it should exist in the new array or false it is shouldn't.
So for the example you provided, it would appear as so:
sounds = sounds.filter((sound) => { sound.id === 1; });
Note you will have to assign the new array, the original array will not change bu running the function itself.
I highly recommend you search for solutions to these problems yourself before creating threads on Slack Overflow or your reputation will quickly decrease.
How do I display an object in my HTML file? (Using Ionic) It seems fairly simple, but it won't work. I retrieve the object like this, from a snapshot of my database path:
this.userPath.subscribe(snapshots => {
this.snapshotValue = snapshots.val()
console.log(this.snapshotValue);
})
And the console looks something like this:
http://i.imgur.com/Kk0A6n5.png (I don't have 'reputation' to post images)
I feel like I've tried everything. Like:
<h1>{{snapshotValue}}</h1> //this returns "[object object]"
<h1>{{snapshotValue.navn}}</h1> //this gives me an error: "cannot read property navn of undefined"
<h1>{{snapshotValue[0]}}</h1> //this gives me an error: "cannot read property '0' of undefined.
How do I get the individual values from this object?
you want to use the async pipe with the elvis operator (?) for observables. Below is using just the elvis.
<h1>{{snapshotValue?.navn}}</h1>
The elvis operator checks if the object exists before checking for a property on the object.
In the future instead of using this
this.userPath.subscribe(snapshots => {
this.snapshotValue = snapshots.val()
console.log(this.snapshotValue);
})
you can do
<h1>{{(userPath | async)?.navn}}</h1>
https://angular.io/api/common/AsyncPipe
The async pipe does the subscribe and gets the latest value for you
This happens when you try to render the view before the data is available.Try the following method
In your component declare a boolean variable
private isDataAvailable:boolean=false;
And in your subscribe method make this true once the data is available
this.userPath.subscribe(snapshots => {
this.snapshotValue = snapshots.val()
console.log(this.snapshotValue);
this.isDataAvailable=true;
})
And reneder the template once the data is available using *ngIf
<div *ngIf="isDataAvailable">
<h1>{{snapshotValue}}</h1>
<h1>{{snapshotValue.navn}}</h1>
<h1>{{snapshotValue[0]}}</h1>
</div>
This should do the trick.You can also use async pipe for the same.Find docs here
<h1>{{snapshotValue | json}}</h1> // this should return you a { stringified json }
I've got a JSON array i'm loading from localstorage which I want to add more items to and put back in local storage. However, i'm getting a bit lost and an error saying concat doesn't exist.
$scope.searchObj = {
term: searchTerm
};
$scope.curObj = $scope.curObj.concat($scope.searchObj);
localStorage.setObject('searchObj', $scope.curObj);
$scope.curObj currently looks like:
Object {term: "fs"}
And I'd like to push the searchTerm (in searchObj) in to curObj so it looks like
{"term":"fs","term":"searchterm"}
$scope.searchObj is not an array but a JSON object.
You actually want to merge two objects. You can use in plain JS :
for (var attrname in $scope.curObj) {
$scope.searchObj[attrname] = $scope.curObj[attrname];
}
Or by using angular extend
$scope.searchObj = angular.extend($scope.searchObj, $scope.curObj);
Use ngStorage for storing object into localstorage and use service $localStorage -
Reference
Use angular.extend(oldobject,newobject) for merging