gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:04:57 26 4
gpt4 key购买 nike

我正在学习 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})

我确信我遗漏了一些小东西!

最佳答案

目前您的浏览器将 "rango/register/" 添加到当前 URL 的末尾。如果您将其更改为 "./""/rango/register/" 它将指向自身,但是这些都不是最佳实践。

为了最佳实践,请改用 {% url "register"%},这样它会在您更改 url.py 时自动更改

例如:

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

关于python - 在 Django 中提交表单时找不到页面(404),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21768084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com