Jquery Ajax 发布到 Django 视图

发布于 2024-12-09 09:15:20 字数 793 浏览 1 评论 0原文

我正在尝试找出将发布数据发送到 Django View 函数的最佳方法。

我目前在 jquery 代码中的内容是这样的:

var name = 'Joe';
var age = 20;

$.ajax({
    url:"/do_something/",
    type: "POST",
    data: {name: name, age: age},
    success:function(response){},
    complete:function(){},
    error:function (xhr, textStatus, thrownError){
        alert("error doing something");
    }
});

数据以 QueryDict 对象形式到达 Django:

<QueryDict: {u'name': [u'Joe'], u'age': [u'20']}>

在视图函数中,我可以访问如下值:

def do_something(request):
    if request.POST:
        name = request.POST.getlist('name')[0]
        age = request.POST.getlist('age')[0]

这感觉有点不对劲(通过 getlist 访问发布数据,然后获取列表中的第一个元素)作为将 post 数据从 jquery 传递到 django 的一种方式。有没有更好的方式发送数据?

I'm trying to figure out the best way to send post data to a Django View function.

What I have currently in my jquery code is something like this:

var name = 'Joe';
var age = 20;

$.ajax({
    url:"/do_something/",
    type: "POST",
    data: {name: name, age: age},
    success:function(response){},
    complete:function(){},
    error:function (xhr, textStatus, thrownError){
        alert("error doing something");
    }
});

The data arrives in Django in a QueryDict object:

<QueryDict: {u'name': [u'Joe'], u'age': [u'20']}>

In the view function, I can access the values like this:

def do_something(request):
    if request.POST:
        name = request.POST.getlist('name')[0]
        age = request.POST.getlist('age')[0]

This feels wrong somehow (accessing the post data through a getlist and then getting the first element in the list) as a way to pass post data from jquery to django. Is there a better way to send data?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

耳根太软 2024-12-16 09:15:20

这可能是执行此操作的“正确方法”,尽管它并不轻松。

您可以使用 [] 表示法从 HttpRequest 对象的 POST 列表中读取 JSON 数据,例如:

JSONdata = request.POST['data']

然后解码 JSON 数据:

dict = simplejson.JSONDecoder().decode( JSONdata ) 

最终将所有 JSON 数据存储在 dict 变量中。用法示例:

username = dict['name']

This might be the "right way" to do this, though it is not any lighter.

You can read the JSON data from HttpRequest object's POST list using [] notation, for example:

JSONdata = request.POST['data']

and then decode the JSON data:

dict = simplejson.JSONDecoder().decode( JSONdata ) 

and you end up having all your JSON data in the dict variable. Example usage:

username = dict['name']
音盲 2024-12-16 09:15:20

为什么你需要使用getlist? Django 的 QueryDict 对象对所有项目使用列表,但简单的 get - 甚至普通的字典访问 - 总是获取第一个项目。所以这个:

name = request.POST['name']

效果很好。

另外,我不明白你最初构建 JS 对象的方式。 ""+name 有什么意义?为什么不只是{name:name,age:age}

Why do you need to use getlist at all? Django's QueryDict objects use lists for all items, but a simple get - or even normal dictionary access - always gets the first item. So this:

name = request.POST['name']

works fine.

Also, I don't understand the way you build up the JS object in the first place. What's the point of ""+name? Why not just {name: name, age: age}?

稚然 2024-12-16 09:15:20

您可以创建一个表单并将保存此数据的代码放入 .save 方法中。这样您还可以免费获得验证。如果您在视图中对 request.POST 和验证进行多次查找,则可能以错误的方式分离了关注点。

如果您只想将此数据保存到模型中,请使用 ModelForm 类(您可以制作仅包含模型的某些字段的表单)。

class PersonForm(forms.Form):
    name = forms.Charfield(max_length=50)
    age = forms.IntegerField(min_value=0, max_value=150)

    def save(self):
        data = self.cleaned_data
        # do what you need here

# protect the view with require_POST decorator
from django.views.decorators.http import require_POST        

@require_POST
def myview(request):
    form = PersonForm(data=request.POST)
    form.save()

表单的另一个好处是您可以在页面中呈现它,并使用 jquery.form.js插件,通过 ajax 提交,无需手动推送任何数据:

$('#personform').ajaxForm({
    success: function one,
    error: function two
})

You can create a form and put the code that saves this data into .save method. This way you also get validation for free. If you do multiple lookups to request.POST and validation in a view, you might have separated the concerns in a wrong way.

If you just want to save this data into a model, use ModelForm class (you can make a form with only some fields of the model).

class PersonForm(forms.Form):
    name = forms.Charfield(max_length=50)
    age = forms.IntegerField(min_value=0, max_value=150)

    def save(self):
        data = self.cleaned_data
        # do what you need here

# protect the view with require_POST decorator
from django.views.decorators.http import require_POST        

@require_POST
def myview(request):
    form = PersonForm(data=request.POST)
    form.save()

Another benefit of a form is that you can render it in a page and, using jquery.form.js plugin, submit it over ajax without pushing any data manually:

$('#personform').ajaxForm({
    success: function one,
    error: function two
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文