在Django视图中显示表和表单

时间:2019-05-09 22:26:49

标签: python django forms view

我试图在同一视图中返回表单和表格,以便它们出现在同一屏幕中。

我知道下面的代码不起作用,这是为了说明我想做的事情-我有CreateManifestFormmanifests = Manifests.objects.all()应该填充模板中存在的表。问题是当我渲染它时-它显示了表单,仅显示了空白表。我已经使用单独的视图填充了表格,所以我知道它是单独设置的,但是如何同时渲染{'form': form}context

Views.py:


def add_manifest(request):
    manifests = Manifests.objects.all()
    context = {
        'manifests' : manifests,
    }

    if request.method == "POST":
        form = CreateManifestForm(request.POST)


        if form.is_valid():
            form.save()
            return redirect('display_orders')

    else:
        form = CreateManifestForm()
        return render(request, 'add_manifest.html', {'form': form})
        return render(request, 'add_manifest.html', context)

1 个答案:

答案 0 :(得分:0)

您只需要返回上下文中所需的所有内容即可。您在那里有2个退货,因此第二个永不发生。

您需要做;


def add_manifest(request):

    if request.method == "POST":
        form = CreateManifestForm(request.POST)

        if form.is_valid():
            form.save()
            return redirect('display_orders')

    # Leave this down here so that you don't hit 
    # the database for manifests on a POST when 
    # the form is valid, because that returns above
    form = CreateManifestForm()
    manifests = Manifests.objects.all()
    context = {
        'form': form,
        'manifests': manifests,
    }

    return render(request, 'add_manifest.html', context)