【问题标题】:Python - Django [error 404 page not found urls]Python - Django [找不到错误 404 页面 url]
【发布时间】:2018-10-31 08:10:22
【问题描述】:

我写了下面一段简单的代码,我只是想检查一下在访问POST方法时是否显示405,而是说找不到页面。

views.py

from django.shortcuts import render, redirect
from django.http import HttpResponse
from .forms import helloform

def index(request):
    form = helloform()
    return render(request, 'hello/index.html', {'form' : form})

def addintodb(request): #trying to invoke this function
    form = helloform(request.POST)
    print(request.POST)
    return redirect(index)

urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('add', views.addintodb, name='addtodb'), #using this url
]

index.html

> form action="{% url 'addtodb' %}" method="POST" role="form" # from here
>     ...                      
>     </form> 

一段时间后我发现,将我的项目 URL 设置为“”可以满足要求。 (即)

我的项目的 urls.py

from django.contrib import admin
from django.urls import path, include


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('hello.urls')) #previously I had path('hellobfs', include('hello.urls'))
]

所以删除我的项目 url 的任何路径都可以让我的应用程序的 url 正常工作而没有“404”错误,有人可以解释为什么吗?

【问题讨论】:

  • 405 不代表成功。
  • 但它实际上应该说 405,当我尝试访问 hellobfs/add 时方法不允许。那些'*'被放置用于在Stackoverflow中将行标记为粗体,
  • 请正确格式化您的代码。在 Python 中它是必不可少的,否则我们可能无法理解。

标签: python django url view


【解决方案1】:

我认为您需要将表单保存在您的 views.py 文件中尝试在您的 , form = helloform(request.POST) 之后添加一个 , form.save()

【讨论】:

    【解决方案2】:

    return redirect(index) 替换为return redirect('/', )。您的代码应如下所示:

    def addintodb(request): #trying to invoke this function
        form = helloform(request.POST)
        print(request.POST)
        return redirect('/', )  #<-- this is the url pattern for your index
    

    【讨论】:

    • 但是根本没有进入函数,遇到404 page not found错误,请在Url部分说明我哪里出错了
    【解决方案3】:

    我想到了这一点,因为我的应用程序中的 urls.py 需要项目和应用程序的 url

    那是 项目地址 ->

    path('hellobfs', include('hello.urls'))
    

    应用的网址 ->

    path('', views.index, name='index'),
    path('adding', views.addnewentry, name='add'),
    

    当我需要遍历添加页面时,我需要提供(我犯错的地方)

    127.0.0.1:8000/hellobfsadding
    

    其中提供了不允许的方法,为了提高可读性,我们可以在项目的 url 中添加一个“/”

    path('hellobfs/', include('hello.urls'))
    

    现在我们可以遍历

    127.0.0.1:8000/hellobfs/adding
    

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 2014-07-20
      • 2013-12-04
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      相关资源
      最近更新 更多