如何在Django中使用URL接收/发送数据?

2024-09-29 23:15:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我是刚到django的。我需要写一个应用程序,读,写数据使用服务链接。你知道吗

例如,我有如下URL:

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

http://site.com/something/DeleteProductById/等等。你知道吗

有没有人能给我举个例子,让我用GET,POST来处理CRUD操作的url。谢谢


Tags: 数据djangocom应用程序httpurlget链接
1条回答
网友
1楼 · 发布于 2024-09-29 23:15:13
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/

相关问题 更多 >

    热门问题