简体   繁体   English

Python-Django [找不到错误404页面的网址]

[英]Python - Django [error 404 page not found urls]

I have written the following simple piece of code, I just wanted to check whether when accessed the POST method, it says 405, but instead it says page not found. 我已经编写了以下简单的代码,我只是想检查访问POST方法时是否显示405,但显示未找到页面。

views.py 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 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 的index.html

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

I figured quite after some time that, having my projects URL to "" gives the required. 一段时间后,我想到将项目URL设置为“”即可满足要求。 (ie) (即)

myproject's urls.py myproject的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'))
]

so removing any path of my project's url allowed me to have myapp's url working without "404" error, can someone explain why? 因此,删除项目的url的任何路径都可以使我的url正常工作而不会出现“ 404”错误,有人可以解释为什么吗?

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

Replace the return redirect(index) with return redirect('/', ) . return redirect(index)替换为return redirect(index) return redirect('/', ) Your code should look like this: 您的代码应如下所示:

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

I figured this, as the urls.py in my app requires both the urls of projects and app 我想通了,因为我的应用程序中的urls.py需要项目和应用程序的URL

that is project url -> 那是项目的URL->

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

app's url -> 应用程序的网址->

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

when I need to traverse to adding page, I need to provide (where I made the mistake) 当我需要遍历添加页面时,我需要提供(我在哪里犯了错误)

127.0.0.1:8000/hellobfsadding

which provided the method not allowed, and to improve readability we can add a '/' in project's url like 它提供了不允许的方法,并且为了提高可读性,我们可以在项目的url中添加“ /”,例如

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

now we can traverse by 现在我们可以穿越

127.0.0.1:8000/hellobfs/adding

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM