Django:如何区分来自同一页面的不同页面的post请求?

2024-09-28 22:56:17 发布

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

我有两页都有表格。但是,这两个页面都向同一个页面发送post请求。如何区分哪个页面发送了请求。你知道吗

虚拟.html(第一页)

<form action="/nda" method='POST'>
        {% csrf_token %}
        <button type="submit" name="submit" id="submit" value="I Agree"  target="_blank">I Agree</button>

        <button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br>
</form>

此页重定向到nda页。你知道吗

保密协议.html(第二页)

此页也重定向到同一页。你知道吗

<form action="/nda"  method='POST'>
        {% csrf_token %}
    <button type="submit" name="submit" id="submit" value="I Agree" target="_self">I Agree</button>
    <button onclick="window.open('/greeting')" target="_self"> I Disagree </button></br>
</form>

我的问题是,在我的观点中,如何区分哪个页面是来自虚拟页面还是来自同一个页面。你知道吗

视图.py

def nda(request):
    if request.method=='POST' :
        # if this is from dummy I want to do this
        return render(request,'mainapp/nda.html',{'user':email.split('@')[0]})

    if request.method=='POST' :
        # if this is from same page that is nda I want to do this
        return render(request,'mainapp/home.html')

我不明白,我该如何以不同的方式处理这两种情况


Tags: formtargetifisrequesthtmlbutton页面
2条回答

如果我正确理解你的问题,你可以在提交按钮中使用name属性

<button type="submit" name="submit1" id="submit" value="I Agree"  target="_blank">I Agree</button

<button type="submit" name="submit2" id="submit" value="I Agree"  target="_blank">I Agree</button

在风景中

def nda(request):
    if request.method=='POST' and 'submit1' in request.POST :
        # do something
        return render(request,'mainapp/nda.html',{'user':email.split('@')[0]})

    elif request.method=='POST' and 'submit2' in request.POST:
        #do something else
        ...

它是如何工作的? 单击submit按钮,服务器正在访问。。 类型为submit的按钮遵循form标记中指定的“action”路径 也就是说,为了使您对不同的页面有一个请求,您需要创建一个额外的url、视图和html

示例:

一个_html.html文件你知道吗

<form action="{% url your_app:name1 %}" method='POST'>
        {% csrf_token %}
        <button type="submit" name="submit" id="submit" value="I Agree"  target="_blank">I Agree</button>

        <button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br>
</form>

你知道吗网址.py地址:

...
url(r'^' + app_name + 'some_path', views_one, name='name1'),

你知道吗视图.py地址:

def views_one(request):
    if request.method=='POST':
        # do something

示例:

两个_html.html文件你知道吗

<form action="{% url your_app:name2 %}" method='POST'>
        {% csrf_token %}
        <button type="submit" name="submit" id="submit" value="I Agree"  target="_blank">I Agree</button>

        <button onclick="window.open('/greeting')" target="_blank"> I Disagree </button></br>
</form>

你知道吗网址.py地址:

...
url(r'^' + app_name + 'some_path', views_two, name='name2'),

你知道吗视图.py地址:

def views_two(request):
    if request.method=='POST':
        # do something

不同之处在于,该操作指向不同的url,因此将被称为不同的视图

相关问题 更多 >