[英]Django httpresponse doesn't work after submit form
I want to submit the form and return to topics page, but it doesn't work. 我想提交表单并返回主题页面,但是它不起作用。 Here is the page before submitting.
这是提交之前的页面。 page before submit
提交前的页面
I enter something and click the button, it doesn't return to the page I want.The error shows as follow: error page 我输入内容并单击按钮,它没有返回到我想要的页面。错误显示如下: 错误页面
It seems like the views.py can't find the right URL, how can I fix it? 似乎views.py无法找到正确的URL,该如何解决?
view.py : 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 : 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 : 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 %}
The problem is in your form, just delete the action: 问题出在您的表单中,只需删除操作即可:
<form method='post'>#instead of
<form action="{% url 'learning_logs:new_topic' %}" method='post'>
if you omit the action automatically return to the same page, also, a better practice in your view would be: 如果您省略该操作,则会自动返回同一页面,因此,您认为更好的做法是:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.