简体   繁体   中英

Ajax is not saving data in DataBase

I am building a BlogApp and I am stuck on a Problem.

What i am trying to do

I am trying to access user's location via JavaScript and saving in the Model's instance in DataBase.

Accessing location is working fine. BUT saving is not working

The Problem

Location's city is not saving in DataBase. When i refresh the page then it doesn't save in DataBase.

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='')
        city = models.CharField(max_length=30,default='')

views.py

def func(request):
    city = request.GET.get('city')
    city.save()

    message = 'Updated'
    return HttpResponse(message)

template (.html)

# Getting city name ( first javascript code ) through IP is working.

<script>

$.ajax({
  url: "https://geolocation-db.com/jsonp",
  jsonpCallback: "callback",
  dataType: "jsonp",
  success: function(location) {
    $('#city').html(location.city);

  }
});

</script>



#This code is for send data to Django.

<script>

    $("city").change(function)(){
        const city = 'city';
        $.ajax({
            url ="{% url 'mains:func' %}",
            data = {
                'city':city,
            } ,
            success.function(data){
                console.log("Update");
            }
        });

    };

</script>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <div>City: <span id="city"></span></div>

I don't know where is the Problem.

Any help would be Appreciated.

Thank You in Advance.

You need to update the profile instance belonging to the user which is referenced on the request. (This is assuming the request is for a logged in user).

def func(request):
    city = request.GET.get('city')
    user = request.user
    profile = Profile.objects.get(user=user)
    profile.city = city
    profile.save()
    message = 'Updated'
    return HttpResponse(message)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM