[英]views.py and urls.py do not connect to perform a function
我有一個連接到django的mysql數據庫,我知道它已連接,因為您已經向我顯示了數據。 但是我做了一個小表格來做測試,並且不保存數據。 該代碼是正確的,因為我已經將其從地方移到了def index (request):
還有,如果您向我發送數據,那是不正確的,因為它沒有在我執行的功能中正確輸入
views.py
from django.shortcuts import render, redirect
from models import Test
def index(request):
test = Test.objects.all()
context = {'test': test }
return render(request, 'test_app/index.html', context)
def create(request):
print request.POST
test = Test(name=request.POST['name'], breed= request.POST['breed'])
test.save()
return redirect('/')
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index),
url(r'^create/$', views.create)
]
的index.html
<form action"/create" method="post">
{% csrf_token %}
<label for="name">Name: <input type="text" name="name" />
</label>
<label for="breed">Breed: <input type="text" name="breed"/>
</label> <input type="submit" value="create" />
</form>
我沒有錯誤,只是如果您發送POST
但沒有任何變量,則不要保存在數據庫中,也不要保存在控制台中。 使用python 2.7和Django 1.1
我不確定我是否理解您的問題,但是在我看來,您的問題是您的表單提交了錯誤的網址。 您的表單指向/create
並且您的網址格式為r'^create/$'
。
要使表單提交到您的創建視圖,請設置正則表達式以可選地匹配斜杠r'^create/?$'
,或將斜杠添加到表單操作action="/create/"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.