提交表单后 Django httpresponse 不起作用
Django httpresponse doesn't work after submit form
我想提交表单和 return 到主题页面,但它不起作用。这是提交前的页面。
page before submit
我输入了一些东西并点击按钮,它没有return到页面我want.The错误显示如下:
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'>
如果您自动省略对同一页面的操作 return,同样,您认为更好的做法是:
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)
我想提交表单和 return 到主题页面,但它不起作用。这是提交前的页面。 page before submit
我输入了一些东西并点击按钮,它没有return到页面我want.The错误显示如下: 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'>
如果您自动省略对同一页面的操作 return,同样,您认为更好的做法是:
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)