在Django中提交表单时找不到页面(404)

时间:2014-02-13 23:46:25

标签: python django

我正在使用Tango With Django教程。我试图让用户注册该应用程序。但是,当用户按下提交按钮时,我收到以下错误消息:

Page not found (404)
Request Method: POST
Request URL:    http://127.0.0.1:8000/rango/register/rango/register/
Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order:
^admin/
^rango/ ^$ [name='index']
^rango/ ^about$ [name='about']
^rango/ ^add_category/$ [name='add_category']
^rango/ ^category/(?P<category_name_url>\w+)/$ [name='category']
^rango/ ^category/(?P<category_name_url>\w+)/add_page/$ [name='add_page']
^rango/ ^register/$ [name='register']
media/(?P<path>.*)
The current URL, rango/register/rango/register/, didn't match any of these.

我不确定这条奇怪的道路是如何建造的。这是注册模板:

<!DOCTYPE html>
<html>
  <head>
    <title>Rango</title>
  </head>

  <body>
    <h1>Register with Rango</h1>

    {% if registered %}
    Rango says: <strong>thank you for registering!</strong>
    <a href="/rango/">Return to the homepage.</a><br />
    {% else %}
    Rango says: <strong>register here!</strong><br />

    <form id="user_form" method="post" action="rango/register/"
      enctype="multipart/form-data">

      {% csrf_token %}

      {{ user_form.as_p }}
      {{ profile_form.as_p }}

      <input type="submit" name="submit" value="Register" />

    </form>
    {% endif %}

  </body>

</html>

要进入注册模板,您需要在索引模板中单击此链接:

<a href="/rango/register">Register Here</a>

这是rango / views.py中的注册函数:

def register(request):
  registered = False

  if request.method == 'POST':
    user_form = UserForm(data=request.POST)
    profile_form = UserProfileForm(data=request.POST)

    if user_form.is_valid() and profile_form.is_valid():
      user = user_form.save()

      user.set_password(user.password)
      user.save()

      profile = profile_form.save(commit=False)
      profile.user = user

      if 'picture' in request.FILES:
        profile.picture = request.FILES['picture']

      profile.save()

      registered = True

    else:
      print user_form.errors, profile_form.errors

  else:
    user_form = UserForm()
    profile_form = UserProfileForm()

  return render(request,
    'rango/register.html',
    {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})

我确信我错过了一些小事!

3 个答案:

答案 0 :(得分:4)

目前,您的浏览器会将"rango/register/"添加到当前网址的末尾。 如果您将其更改为"./""/rango/register/",则会将其更改为自己,但这些并非最佳做法。

为了获得最佳实践,请使用{% url "register" %},这样会自动更改,因为您更改了url.py

e.g:

<form id="user_form" method="post" action="{% url "register" %}"
      enctype="multipart/form-data">

答案 1 :(得分:0)

<form action>属性很可能是错误的。

现在它相对于:

   rango/register/rango/register/

   <form id="user_form" method="post" action="rango/register/" <--- relative

快速解决方法尝试(不是最佳做法):

   <form id="user_form" method="post" action="/rango/register/" 

代替。

了解相对URL如何在HTML页面中工作,这应该揭开神秘面纱。

答案 2 :(得分:0)

似乎问题出在你的URLs.py页面上 - 好像你没有设置django的url重写部分