首页 文章

Django:如何从同一页面传递表单的输入内容?

提问于
浏览
0

我刚刚开始使用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输入字段形式,如下所示:

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

我可以知道如何解决这个问题吗?

谢谢!

2 回答

  • 1

    只是这种类型的答案 . 如果你想发布到同一个 url ,你现在正在使用 . 试试这个并将 def hello(request, name) 改为 def hello(request) .

    action=""
    

    否则如果 urls.py

    urlpatterns = patterns('app.views',
    url(r'^$', view="index", name="app_index"),
    

    试试这个

    action="{% url app_index %}"
    

    正如我发现的那样,你可以申请

    action="{% url helloworld:index %}"
    

    希望这可以帮助

    For your answer updated . 试试这个

    <form method="post" action="{% url "index" %}">
    
  • 0

    你需要改变这一行

    <form method="post" action="{% url 'helloworld:hello' %}">
    

    <form method="post" action="{% 'helloworld:hello' %}">
    

相关问题