簡體   English   中英

Python-Django [找不到錯誤404頁面的網址]

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

我已經編寫了以下簡單的代碼,我只是想檢查訪問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設置為“”即可滿足要求。 (即)

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'))
]

因此,刪除項目的url的任何路徑都可以使我的url正常工作而不會出現“ 404”錯誤,有人可以解釋為什么嗎?

我認為您需要將表單保存在views.py文件中,請嘗試在form = helloform(request.POST)之后添加一個form.save()。

return redirect(index)替換為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

我想通了,因為我的應用程序中的urls.py需要項目和應用程序的URL

那是項目的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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM