使用POST和GET选项在html上传递上下文

时间:2016-11-07 23:16:50

标签: html django django-templates django-views

我有一个带有各种提交按钮的html页面:

<h3>Add Address</h3>
    <form method="post">
        {% csrf_token %}
        ...
        <input type="submit" value="Add" name="_add_add">
    </form>
<h3> Update values </h3>
    <form method="post">
        {% csrf_token %}
        ...
        <input type="submit" value="Add" name="_update">
    </form>
<h3>Address</h3>
    <form method="get">
        ...display...

我的view.py是:

def property(request):
    if request.method == 'POST':
        if '_update' in request.POST:
            ...update values...
        elif '_add_add' in request.POST:
            ...add addres....
            Context = {"name_for_template":"value"}
    else:
        ... graph default values...
        Context = {"name_for_template":"value"}

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

如果没有POST并且只是一个GET(就像被重定向到页面一样),我在上下文中遇到了一个CSRF错误(并且它要求我使用request_context)。是否有可能(以及如何)自动发送GET的默认上下文,并为POST发送不同的上下文而不会产生CSRF错误?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此编辑代码

def property(request):
    context = {}
    if request.method == 'POST':
        if '_update' in request.POST:
            ...update values...
        elif '_add_add' in request.POST:
            ...add addres....
            context["name_for_template"]= "value"
    else:
        ... graph default values...
        context["name_for_template"]= "value"
return render(request, 'address.html', context)

如果不起作用,请分享您的代码