如何通过HTML中的JavaScript在Django中保存模型实例 [英] How to save model instance in Django through JavaScript in HTML

查看:58
本文介绍了如何通过HTML中的JavaScript在Django中保存模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建BlogApp,但遇到问题

I am Building a BlogApp and I am stuck on a Problem

我要做什么

我在模型中创建了一个名为 user_location 的实例.我在 template 中访问了它,并编写了 JavaScript 代码以使用 JavaScript 访问 User's Location ,但是我想要我的模型实例将 JavaScript的输出国家/地区保存在数据库中.

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.

问题

我不知道如何通过JavaScript保存模型实例.

I don't know how to save model instance through JavaScript.

models.py

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

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 }}

我尝试了什么

我还尝试了> THIS .但是它对我不起作用.

I also tried THIS. BUT it didn't work for me.

我不知道该怎么办.

任何帮助都会得到赞赏.

Any help would be Appreciated.

先谢谢您

推荐答案

使用Ajax将数据发送到后端,然后让django完成.

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

这篇关于如何通过HTML中的JavaScript在Django中保存模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆