Creating a JSON Object in views and passing it in HTML - javascript

views.py - Django 2.0.2
def hotels(request):
list_of_hotels = Hotel.objects.order_by('hotel_name')
template = loader.get_template('myapp/hotels.html')
data = {}
for each in list_of_hotels:
data[str(each.hotel_name)] = 'null'
json_data = json.dumps(data)
context = {
'list_of_hotels': list_of_hotels,
'json_data': json_data,
}
return HttpResponse(template.render(context, request))
hotels.html
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">search</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label for="autocomplete-input">Search</label>
</div>
</div>
</div>
</div>
<script>
var jsonObj = "{{json_data}}";
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: jsonObj,
});
});
</script>
I'm trying to parse a JSON Object from Django views into a script located inside the corresponding HTML page. I tried everything, but it just doesn't seem to work. I searched Stack Overflow for about an hour now, and based on all the answers came to these snippets of code, which still don't work. Any leads on how to go about it would be highly appreciated!
P.S: In the script in hotels.html, the data takes in a JSON Object. For more details on the initialisation, refer to this.
P.P.S: I am an absolute noob in JavaScript/ jQuery.

Found a solution to my own problem after a lot of tries. Thanks to anyone who tried to help me. :)
hotels.html
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">search</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label for="autocomplete-input">Search</label>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
var jsonObj = {{ json_data|safe }};
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: jsonObj,
});
});
</script>
views.py
def hotels(request):
list_of_hotels = Hotel.objects.order_by('hotel_name')
template = loader.get_template('myapp/hotels.html')
data = {}
for each in list_of_hotels:
data[str(each.hotel_name)] = None
json_data = json.dumps(data)
context = {
'list_of_hotels': list_of_hotels,
'json_data': json_data,
}
return HttpResponse(template.render(context, request))

Related

How do I get the values of a BeginCollectionItem in javascript

I want to get values of a BeginCollectionItem using javascript but it seems like i am not winning
my html
#using HtmlHelpers.BeginCollectionItemCore
#using E_Commerce.Application.Models
#model ProductImageModel
<li class="mb-2">
#using (Html.BeginCollectionItem("ProductImages"))
{
Html.RenderPartial("_imagesPartial", Model);
}
</li>
the _imagesPartial html
#model E_Commerce.Application.Models.ProductImageModel
<div class="col-md-12 row mb-2">
<div class="col-md-4 imageDiv">
<img class="border rounded" />
</div>
<div class="col-md-4">
<input type="file" asp-for="File" onchange="uploadImageTest(this)" />
</div>
<div class="col-md-4">
Remove
</div>
</div>
and my javascript
let addNewImagesFormSubmit = (event) => {
var Id = $("#Id").val();
var productImages = $("#ProductImages").val();
$.ajax({
url: "#Url.Action("AddNewImages","ProductImage")",
data: {
Id: Id,
productImages:productImages
},
success: function (data) {
$("#productImagesDiv").html(data);
}
})
}
the server side does not seem to get any images when using javascript to get the BeginCollectionItem.
how do i get it to work

How to add a hyperlink to the data in the created div using API

I am retrieving data based on users input (zipcode), using API. They get three types of information, name of the institution, address and webpage. I would like to add a hyperlink to the webpage line (<p>${data[i].website}</p>) but none of my ideas worked. Thank you, guys.
function ajaxCallNY(zipcode){
$.ajax({
url: "https://data.cityofnewyork.us/resource/72ss-25qh.json?zip_code=" + zipcode,
type: "GET",
data: {
"$limit" : 50,
"$$app_token" : app_token
}
}).done(function(data) {
console.log(data);
for (var i=0; i<data.length; i++){
var nyDiv = $(`<div class="col s12 m6">
<div class="card blue-grey darken-1">
<div class="card-content white-text">
<span class"card-title">${data[i].agency_id}</span>
<p>${data[i].address}</p>
<p>${data[i].website}</p>
</div>
</div>
</div>
`);
$("#zipcode").append(nyDiv);
}
});
}
Since you're using template literals already, you can do it like this:
`
<div class="col s12 m6">
<p>${data[i].address}</p>
<p>Link</p>
</div>
</div>
`

How do I pass usernames from the User model in django to autocomplete

I am implementing autocomplete on a html page on my django website.
I am looking to use the autocomplete from materialize
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label for="autocomplete-input">Autocomplete</label>
</div>
</div>
</div>
</div>
Materialize shows how data can be passed to this autocomplete
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.autocomplete');
var instances = M.Autocomplete.init(elems, options);
});
// Or with jQuery
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: {
"Apple": null,
"Microsoft": null,
"Google": 'https://placehold.it/250x250'
},
});
});
I understand the second part and can implement it. However I do not understand how the first part works, which I think is what I will need.
My need is to pass the usernames from the User model in django to this autocomplete. How would I go about doing this
You would pass the usernames into the context like this:
view
class YourView(View):
def get(self, request, *args, **kwargs):
return render(request, 'yourpage.html', {"users": User.objects.all()}
html (cannot be in .js file, since django needs to parse the file)
var usernames = {
{% for user in users %}
{{ user.username }}: "{{ user.username }}",
{% endfor %}
}
$(document).ready(function(){
$('input.autocomplete').autocomplete({
data: usernames,
});
});

Showing changes without refreshing in VueJS

I'm so new in VueJS and still don't control much of its funcionalities,
I'm trying when I update or delete something in my window not need to refresh to see the changes...how can I do it, please?
My functions work perfectly in my controller, just need to solve the question of seeing changes.
Here I post my code if it helps...thank you very much!!
UpdateProfile.vue:
<div class="field">
<label class="label">Schedules</label>
<!--Edit and Delete Schedules-->
<div v-for="schedule in sortedDays(data.schedulesDisplayed)" class="control">
<div class="container">
<div class="field">
<label class="label">Week Day: {{schedule.week_day}}</label>
</div>
<div class="row">
<div class="col">
<div class="row">
Opening Time: <input class="input" type="text" placeholder="Pub schedules" v-model="schedule.opening_time">
</div>
</div>
<div class="col">
<div class="row">
Closing Time: <input class="input" type="text" placeholder="Pub schedules" v-model="schedule.closing_time">
</div>
</div>
</div>
<div class="field">
<div class="buttons is-left">
<div class="button is-info" #click="updatePubSchedule(schedule)">
<span class="icon"><i class="fas fa-save fa-lg"></i></span>
<span>Save</span>
</div>
<div class="button is-danger" #click="deletePubSchedule(schedule)">
<span class="icon"><i class="far fa-trash-alt"></i></span>
<span>Delete Schedule</span>
</div>
</div>
</div>
</div>
</div>
</div>
updatePubSchedule(schedule){
var instance = this;
this.api.put('/pubschedules/update/' + this.data.id, schedule).then(response => {
console.log(schedule);
//data = response.data;
instance = response.data;
});
},
deletePubSchedule(schedule){
var instance = this;
this.api.delete('/pubschedules/delete/' + this.data.id, schedule).then(response => {
//data = response.data;
instance = response.data;
});
},
And in my controller:
/**
* #param Pub $pub
*/
public function updatePubSchedule(Pub $pub)
{
//json_die(request()->all());
Schedule::where([
['pub_id','=', $pub->id],
['week_day' ,'=', request()->get('week_day')]
])->update(request()->all());
}
/**
* #param Pub $pub
*/
public function deletePubSchedule(Pub $pub)
{
Schedule::where([
['pub_id','=', $pub->id],
['week_day' ,'=', request()->get('week_day')]
])->delete();
}
I don't know how you get your initial data but you can have a GET request that gets fresh data from the laravel after you update/delete initial data.
With the response from that request you can update your data.schedulesDisplayed prop.
Important! You need to set the :key attribute in the div that uses v-for rendering like this
<div v-for="(schedule, index) in sortedDays(data.schedulesDisplayed)" :key="index" class="control">
I used the index for the sake of this example but you should use a unique property of sortedDays return.

Removing selected row from an array using splice in angularjs

I have an issue in removing the particular item from an array.I have tried using splice but, the last row is removing instead of the particular row.I am providing the plunker link here :
$scope.rows.splice($index, 1);
https://plnkr.co/edit/WETSLqOXlTwiHq4p9IUt?p=preview
Any help would be appreciated . Thanks
just try the following
http://jsfiddle.net/oymo9g2f/2/
you have some problem with your array splice
Not quite sure what you're trying to accomplish (as your code looks like you are quite new to AngularJS, but I created a different (but similar) implementation that should fit your needs (it's easier to read IMHO and is scalable):
HTML:
<div class="card ">
<form name="add_destination_form" class="col s12" ng-submit="add_destination_form.$valid && addDestination_Details(destination_details)" novalidate>
<div class="row" ng-repeat="row in rows track by $index">
<div class="col s12 m4" >
<label for="destination_features1" >Features</label>
<textarea id="destination_features1" name="destination_features1_{{$index}}" ng-model="destination_details.destination_features1[$index]" placeholder="Data Here" type="text" ></textarea>
</div>
<button ng-show="show_removebtn" id="removeButton" ng-click="removeDynamically($index)" type="button">Remove</button>
</div>
<div class="col s12 m4">
<button class="waves-effect waves-light btn" ng-click="addDynamically()" type="button">Add More</button>
</div>
<div class="row">
<div class="col s12 m4">
<button type="submit">Submit</button>
</div>
</div>
</form>
</div>
JavaScript:
$scope.rows = [{
"row_num": 0,
"text": ""
}];
$scope.addDynamically = function (index) {
console.log(index);
$scope.rows.push({
"row_num": index,
"text": ""
});
};
$scope.removeDynamically = function (index) {
$scope.rows.splice(index, 1);
};
Plunker
just use this code. For text area used ng-model="row.value" and related change in controller
in html: just shown ng-repeat part
<div class="row" ng-repeat="row in rows track by $index">
<div class="col s12 m4" >
<label for="destination_features1" >Features</label>
<textarea id="destination_features1" name="destination_features1_{{$index}}" ng-model="row.value" placeholder="Data Here" type="text" ></textarea>
</div>
<button ng-show="show_removebtn" id="removeButton" ng-click="removeDynamically($index)" type="button">Remove</button>
</div>
and in controller:
$scope.rows = [];
$scope.current_rows = 0;
$scope.destination_details = {};
$scope.rows.push({
row_num: $scope.current_rows,
value: ''
});
$scope.addDynamically = function() {
$scope.current_rows += 1;
$scope.rows.push({
row_num: $scope.current_rows,
value: ''
});
if ($scope.rows.length > 1) {
$scope.show_removebtn = true;
}
};
$scope.removeDynamically = function(index) {
if (index > -1) {
$scope.rows.splice(index, 1);
}
};
You need to add line:
$scope.destination_details = {"destination_features1": ['1']};
at the beginning.
Also need to remove model properly when removing element:
$scope.destination_details.destination_features1.splice($index, 1);
https://plnkr.co/edit/pe44Moqe7ymegYFTrXJu?p=preview

Categories

Resources