gpt4 book ai didi

python - 提交表单后,Django httpresponse 不起作用

转载 作者:行者123 更新时间:2023-12-01 02:31:55 25 4
gpt4 key购买 nike

我想提交表单并返回主题页面,但不起作用。这是提交前的页面。 page before submit

我输入一些内容并点击按钮,它没有返回到我想要的页面。错误显示如下: error page

views.py 似乎找不到正确的 URL,我该如何修复它?

view.py:

def new_topic(request):
if request.method != "POST":
form = TopicForm()
else:
form = TopicForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('leraning_log:topics'))

context = {'form':form}
return render(request,'learning_logs/new_topic.html',context)

urls.py:

urlpatterns = [

url(r'^topics/$',views.topics,name='topics'),

url(r'^topics/(?P<topic_id>\d+)/$',views.topic,name='topic'),

url(r'^new_topic/$',views.new_topic,name='new_topic'),
]

new_topic.html:

{% extends "learning_logs/base.html" %}

{% block content %}
<p>Add a new topic:</p>

<form action="{% url 'learning_logs:new_topic' %} method='post'>
{% csrf_token %}
{{form.as_p }}
<button name="submit">add topic</button>
</form>
{% endblock content %}

最佳答案

问题出在你的表单上,只需删除该操作即可:

 <form method='post'>#instead of
<form action="{% url 'learning_logs:new_topic' %}" method='post'>

如果您省略自动返回同一页面的操作,您认为更好的做法是:

def new_topic(request):
if request.method = "POST":
form = TopicForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('leraning_log:topics'))

else:
form = TopicForm()

context = {'form':form}
return render(request,'learning_logs/new_topic.html',context)

关于python - 提交表单后,Django httpresponse 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46722353/

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