How to save model instance in Django through JavaScript in HTML - javascript

I am Building a BlogApp and I am stuck on a Problem
What i am trying to do
I made a instance named user_location in model. I accessed it in template and I write JavaScript code to access User's Location using JavaScript BUT i want my model instance to save the JavaScript's Output country in the Database.
The Problem
I don't know how to save model instance through JavaScript.
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
full_name = models.CharField(max_length=100,default='')
user_location = models.CharField(mac_length=100,default'')
profile.html
<script>
$.ajax({
url: "https://geolocation-db.com/jsonp",
jsonpCallback: "callback",
dataType: "jsonp",
success: function(location) {
$('#country').html(location.country_name);
}
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div>Country: <span id="country"></span></div>
#This is my model instance.
{{ profile.user_location }}
What have i tried
I also tried THIS. BUT it didn't work for me.
I don't know what to do.
Any help would be Appreciated.
Thank You in Advance.

Use Ajax to send your data to the backend and let django do it's thing.

You can use fetch api from javascript to storing the data from javascript in ur model db like fetch(your website route) where u had created your form for post request.
You can create post request on ur route to save ur db.
Example-url = "your website post request route"
params =
method:'post',
headers:
'Content-Type': 'application/json'
body: data
fetch(url, params).then(response=> response.json())
.then(data => console.log(data)
)*/

Related

How to insert data into my database with php without form?

Please help me, I have a game on my website, but I don't know how to insert that poin into my database because I do not use a form.
I also want to ask, how to enter data without using form into the global variable $_POST? (You can use PHP or javascript for it)
<div class="container">
<h2>
Your point :
<span class="poin">120</span> <!-- It will be inserted into the database -->
</h2>
</div>
Without a form, you can send a POST request to your server by using the fetch API.
Just add the following JavaScript code:
const poin = document.querySelector('.container .point').textContent
;(async () => {
await fetch('host:port', {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify({ point })
})
})()
And replace 'host:port' to the correct host and port (of your server).
With document.querySelector('.container .point') you are selecting the DOM-element which CSS-selector is '.point'.
fetch accepts the following parameters: url and [options]. The [options] (which is optional) is a object with the following properties: method, headers and body, among others.

How to upload a JSON that includes an image file to a Spring Boot Rest API

I am currently using the fetch API to post a JSON object to a REST API created with Spring Boot. I am using formData to read in the form data and store it in a JSON object:
const data = new FormData(form);
const formJson = Object.fromEntries(data.entries());
let responsePromise = await fetch(
"http://localhost:8080/api/v1/student?id=" + studentId, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(formJson)
});
The Spring Boot backend expects a JSON that corresponds to the Student entity class, which will eventually be stored in my database:
#PutMapping
public ResponseEntity<Student> updateStudent(#RequestBody Student student, #RequestParam Long id) {
Student currentDatabaseEntry = studentService.getStudent(id);
currentDatabaseEntry.setFirstName(student.getFirstName());
...
return new ResponseEntity<>(currentDatabaseEntry , HttpStatus.FOUND);
}
This works fine.
Now, I have added a variable to the Student entity, which is of type byte[] and is suppossed to store an image of the student. So, I want to add an entry to my JSON object with key image and the value being a multipart file (the value of an input field of type "file").
From what I have read on the internet, it seems that whenever I want to upload a file, I should not upload a JSON, but instead the formData object. I fail to see how to handle this request on my backend though - doesn't Spring Boot expect the #RequestBody of the PUT request to be a JSON that resembles my Student entity?
Anyways, does anyone know how to achieve this?

url to fetch with parameter for django view

I'm facing a problem with my javascript code when trying to use AJAX instead of href link.
I need to hit a django url that looks like this (Django 2.2):
path('one-time/<str:product_url>/', OneTimeProductView.as_view(), name='one_time_product')
the origial code in the django template was:
{{product}}
I now want to use ajax call to make the whole process opened inside of a modal. In my javascript code my fetch function looks like this:
function handleAccess(){
var url = "{% url 'one_time_product' product %}" ;
fetch(url, {
method: "POST",
headers: {
"X-CSRFToken": '{{csrf_token}}',
"Accept": "application/json",
"Content-Type": "application/json"
}
})
.then (response => {
response.json();
})
.then (data => {
console.log(data);
})
};
I know i'm missing something related to the params in the url variable but I just don't know how to add it properly so that i fit the url path.
This is the error that I get when I hit the button
NoReverseMatch at /one-time/ Reverse for 'one_time_product' with no
arguments not found. 1 pattern(s) tried:
['one\-time\/(?P<product_url>[^/]+)\/$']
How should I write the url in the fetch function ?
I will appreciate and anyone can point me into the right direction here.
Thanks
It was a tricky one.
I solved it with the back-end dev.
var url = "{% url 'one_time_product' product_url=0 %}".replace('0', {{ product }}) ;
You have a named parameter in the URL definition (product_url).
On top of my head, you should use the url templatetag like this:
var url = "{% url 'one_time_product' product_url=product.url %}" ;
Change the product.url to the actual url (or slug) from your product model.

How to name a audio file when saving into server with POST

I've being developing a solution for my webpage with Django and javascript, it's a record button so that the user can send feedback and I can store it into the server.
The plan is putting a text input where the user can introduce its name and a file is created with that name. This is my code by now. Can anyone help me with this?
Python views.py
def voice_request(request):
f = open('./Grabaciones/file.wav', 'wb')
f.write(request.body)
f.close()
return HttpResponse('audio received')
Javascript part
function sendData(data) {
let csrftoken = getCookie('csrftoken');
let response=fetch("/salud/voice_request/", {
method: "post",
body: data,
headers: { "X-CSRFToken": csrftoken },
})
}
Welcome at SO.
You have to offer some text input form to the user in order to enable him to send some context. On the backend site, you would then push the data to the database using a Django model which is basically the toolbox for handling data in Django.
Kindly refer to the docu to get a deep dive into it:
https://docs.djangoproject.com/en/3.0/topics/forms/

How to import path of api.php in frontend

Here is one sample post request which is in script.js.I want to send data from this request and store in beckend.So i have created api.php file which has All routes associated with controllers.
In api.php , My reqeust route is..
Route::post('/task/create/{task_id}','TasksController#create');
Request in script.js..
var request = $http({
method: "POST",
url: "/api/task/create/1", //// Changes will made here
data: {id: index, title: $scope.title},
headers: {'Content-Type': 'application/json'}
}).catch(function(data){
alert("error");
});
I am running this files on local server.
http://127.0.0.1:8000/api/task/create/1
I guess I am inserting the wrong url and i dont how to import that api.php file here and call after making request.So please suggest me to do that.
To call php script you should use
http://127.0.0.1:8000/api.php?taskid=1
inside PHP script you should use
$taskid = $_GET['taskid'];
As far as I get you try use Express based syntax inside php. If you are using php script to generate JS then you can do that only for front-end

Categories

Resources