简体   繁体   English

Ajax 未在数据库中保存数据

[英]Ajax is not saving data in DataBase

I am building a BlogApp and I am stuck on a Problem.我正在构建一个 BlogApp,但我遇到了一个问题。

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.我正在尝试通过JavaScript访问用户的位置并将模型的实例保存在数据库中。

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模型.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视图.py

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

    message = 'Updated'
    return HttpResponse(message)

template (.html)模板 (.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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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