【问题标题】:Django httpresponse doesn't work after submit form提交表单后 Django httpresponse 不起作用
【发布时间】:2018-03-25 03:26:48
【问题描述】:

我想提交表单并返回主题页面,但它不起作用。这是提交前的页面。 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 %}

【问题讨论】:

  • 你能添加你的模板吗?
  • 多谢提醒,已添加。
  • 看代码着色..action=""没有正确关闭

标签: python django forms httpresponse


【解决方案1】:

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

 <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)

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 1970-01-01
    • 2018-06-11
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多