【问题标题】:How can I create redirect button with post method in Django template如何在 Django 模板中使用 post 方法创建重定向按钮
【发布时间】:2020-05-07 17:46:31
【问题描述】:

我正在尝试在 Django 模板中创建一个按钮,该按钮将重定向到另一个 URL。但是由于 Django 无法识别 urls.py 中描述的 URL 路径,因此出现错误 404。

HTML 部分

<form method="post" action='sts'>
{% csrf_token %}
 <button class="btn btn-outline-success my-2 my-sm-0" type="submit" name="cts_link">cts</button>
</form>

urls.py

from django.conf.urls import include, url
from django.contrib import admin
from rtRegRes.views import units
from rtRegRes.views import spartan

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^units/$', units),
    url(r'^units/sts/?$', spartan),
]

views.py

from django.shortcuts import render, redirect, reverse, render_to_response
from .models import rt_reg_res
from django.http import HttpResponse, JsonResponse

def units(request):
    """Return main webpage"""
    return render_to_response('runtime.html')

def spartan(request):
    """Link to the other unit webpages"""
    table = rt_reg_res.objects.all()
    if request.method == 'POST':
        qatables = request.POST.get("cts_link")
        if qatables:
            return render(request, 'cts.html', {'table': table})

单击按钮出现以下错误消息: enter image description here

谁能指出我的代码有什么问题

谢谢

【问题讨论】:

    标签: html django python-3.x


    【解决方案1】:
    from django.conf.urls import include, url
    from django.contrib import admin
    from rtRegRes.views import spartan , units
    
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^units/$', units),
        url(r'^units/sts/?$', spartan, name='sts'),
    ]
    

    <form method="post" action='sts'>
    {% csrf_token %}
     <button class="btn btn-outline-success my-2 my-sm-0" type="submit" name="cts_link">cts</button>
    </form>
    

    【讨论】:

      【解决方案2】:

      交换 url 的顺序应该会有所帮助。

      urlpatterns = [
          url(r'^admin/', admin.site.urls),
          url(r'^units/sts/?$', spartan),
          url(r'^units/$', units),
      ]
      

      【讨论】:

      • 感谢您的回复。我试过了,但没有帮助...谢谢
      【解决方案3】:

      真可惜,我白白浪费了我的时间((我的代码是正确的,我只是忘记在更改后重新运行服务器,每次重新加载页面并没有看到真正的变化。无论如何,谢谢大家的回复!!

      【讨论】:

        猜你喜欢
        • 2021-03-11
        • 2021-09-19
        • 2021-03-31
        • 1970-01-01
        • 2018-11-17
        • 2010-11-18
        • 2017-02-14
        • 2012-05-29
        • 1970-01-01
        相关资源
        最近更新 更多