【发布时间】:2015-03-26 06:10:06
【问题描述】:
我刚开始使用 Django,对整个事情还很陌生。
我浏览了整个教程 https://docs.djangoproject.com/en/1.7/intro/tutorial03/ ,包括设置数据库和编写一个简单的表单。
为了开始我的 Django 之旅,我计划编写一个在 localhost 上运行的简单应用程序。而且我在通过表单传递输入时遇到了问题。
我在 models.py 中创建了一个具有 1 个属性的 Name 类
#name of the person
value = models.CharField(max_length=50)
在我的索引链接:http://localhost:8000/helloworld/,它包含一个简单的 1-input-field 形式如下:
<form method="post" action="{% url 'helloworld:hello' %}">
{% csrf_token %}
Enter Name: <input size="80" name="link" type="text">
<button type="submit">Submit</button>
</form>
表单的目的是将输入数据返回到同一链接(http://localhost:8000/helloworld/),输入消息为:
"Welcome [NAME], Hello World"
在我的views.py中,写了如下方法:
def hello(request,name):
p = get_object_or_404(Link, pk=name)
try:
input_link = p.choice_set.get(pk=request.POST['link'])
except (KeyError, Link.DoesNotExist):
return render(request, 'helloworld/index.html',{
'error_message': "You did not enter a name",
})
else:
return HttpResponseRedirect(reverse('helloworld:index', args=(p.value)))
如果我访问页面http://localhost:8000/helloworld/,并在字段中输入数据并单击提交,它会将我带到页面
Page not found (404)
Request Method: POST
Request URL: http://localhost:8000/helloworld/url%20'helloworld:hello'
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^helloworld/ ^$ [name='index']
^helloworld/ ^(?P<pk>\d+)/$ [name='detail']
^helloworld/ ^(?P<pk>\d+)/results/$ [name='results']
^helloworld/ ^(?P<question_id>\d+)/vote/$ [name='vote']
^admin/
The current URL, helloworld/url 'helloworld:hello', didn't match any of these.
urls.py 中的内容来自https://docs.djangoproject.com/en/1.7/intro/tutorial04/#amend-urlconf
根据要求,urls.py的内容:
from django.conf.urls import patterns, url
from domparser import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
)
请问我该如何解决这个问题?
谢谢!
【问题讨论】:
-
你能显示 urls.py 吗?
-
你试过
action=""吗?