0

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.

Lars
  • 1,234
  • 1
  • 8
  • 31

2 Answers2

1

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

Chymdy
  • 662
  • 4
  • 14
-1

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)
)*/
  • Can you please explain clean ? – Lars Mar 13 '21 at 07:12
  • Oh i had pasted full code of javascript but i dont know why the code is broken i can give advice to read the fetch api of javascript or if u using jQuery ajex you can use post request which will post your data to ur db – Sumit kumar Mar 13 '21 at 07:18
  • OKay Thanks, I will try in few minutes – Lars Mar 13 '21 at 07:19