0

Django:是否有通用处理程序将 POST 对象直接插入数据库?我发现自己编写了很多看起来像这样的处理程序。

def ajax_storeObject(request):
    if request.method == 'POST':
         Object(
                field1 = request.POST["field1"],
                field2 = request.POST["field2"],
                field3 = request.POST["field3"],
                field4 = request.POST["field4"],
          ).save()
          return HttpResponse(json.dumps({"status":"Success"}), mimetype="application/json")
    return HttpResponse(json.dumps({"status":"Failed"}), mimetype="application/json")

似乎可以有一个单一的通用视图来处理这种事情。这样的观点存在吗?

编辑:顺便说一句,我对模型表单很满意,但我在这里看到的用例更窄:不基于标准表单的 RESTful AJAX 调用(例如,用户操作页面上的对象,以及发送 REST 调用以通知服务器。)。

4

3 回答 3

1

你看过模型表格吗?

于 2011-12-31T16:01:53.777 回答
1

There is nothing about forms that requires you to actually draw a form. ModelForms are the right thing to use if you're not going to go with piston or tastypie or something like that.

Put this in your page: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

class ObjectAjaxForm(forms.ModelForm):
  class Meta:
     model = Object
     fields = ("field1", "field2", "field3", "field4")


#or, if you don't want the "free" csrf protection
#@csrf_exempt
def ajax_store_object(request):
    #request.POST can be substituted with any dictionary/dictionary like object
    form = ObjectAjaxForm(request.POST)
    if form.is_valid():
      form.save()
      return HttpResponse(json.dumps({"status":"Success"}), mimetype="application/json")
    else:
      return HttpResponse(json.dumps({"status":"Failed"}), mimetype="application/json")
于 2012-01-01T01:26:31.687 回答
0

据我所知,没有通用的 Ajax 视图,但也许您正在寻找这个?

Object(**request.POST).create()

当然,您需要确保request.POST不包含您不想放入模型中的任何内容(例如“提交”字段)。

于 2011-12-31T17:06:14.510 回答