如何使用django中的URL接收/ posta数据?

时间:2013-10-07 07:55:17

标签: python django post get django-rest-framework

我是django的新手。我需要编写一个使用服务链接读取,写入数据的应用程序。

例如,我有一个像:

这样的网址

http://site.com/something/LoadProducts/

http://site.com/something/DeleteProductById/等等。

任何人都可以给我任何使用GET的示例,CRUD操作的POST网址。感谢

1 个答案:

答案 0 :(得分:1)

from django.shortcuts import render, get_object_or_404
# form imports here
# model imports here

# get all objects
def get_view(request):
    objects = YourModel.objects.all()
    return render(request, 'all-objects.html', {'objects': objects}

# make a new object
def make_new_obj(request):
    form = YourForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
    return render(request, 'make-new-obj.html', {'form': form}

# get an object by id
def get_single_object_view(request, id):
    obj = get_object_or_404(YourModel, pk=id)
    return render(request, 'obj-detail.html', {'obj': obj}

# update an object
def update_obj(request, id):
    obj = get_object_or_404(YourModel, pk=id)
    form = YourForm(request.POST or None, instance=obj)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
    return render(request, 'update-obj.html',
        {'obj': obj, 'form': form}

# delete an object
def delete_obj(request, id):
    obj = get_object_or_404(YourModel, pk=id)
    obj.delete()
    # do something else like redirect to the object index, etc
    # you'll probably want to make this a two-step process

显然,这里有很多代码可以组合,所以根据需要混合搭配。所有这些代码都在Django文档中得到了很好的介绍......

模型实例参考:https://docs.djangoproject.com/en/1.5/ref/models/instances/

使用表单:https://docs.djangoproject.com/en/1.5/topics/forms/