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

标签 python django forms httpresponse

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

相关文章:

python - 如何折叠重叠间隔[开始-结束]并保持较小?

python - 按街道地址分组并将其拆分为街道名称和号码

python - NumPy 的 C-API : scalar multiplication in C

python - 在 python 中获取行百分比来绘制

django 在模板中调用无请求 View 函数

javascript - React - 表单提交后清除电子邮件输入字段

python - 为什么 View 函数在 Django 中需要一个请求参数?

python - 操作错误 : No such Column

javascript - 最有效的表单验证

django - 如何覆盖Django AuthenticationForm输入CSS类?