我想提交表单并返回主题页面,但它不起作用。这是提交前的页面。 page before submit
我输入内容并单击按钮,它不会返回到我想要的页面。错误显示如下: error page
看起来好像是找不到合适的网址,我该如何解决?
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 %}
答案 0 :(得分:2)
问题在于您的表单,只需删除操作:
<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)