-3

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

例如,我有一个像这样的 URL:

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

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

谁能给我任何使用 GET、POST url 进行 CRUD 操作的示例。谢谢

4

1 回答 1

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/

于 2013-10-07T12:19:11.310 回答