代码之家  ›  专栏  ›  技术社区  ›  Руfarmer

Django httpresponse在提交表单后不工作

  •  1
  • Руfarmer  · 技术社区  · 7 年前

    page before submit

    我输入一些东西并单击按钮,它不会返回到我想要的页面。错误显示如下: error page

    看起来像是风景。py找不到正确的URL,如何修复?

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

    URL。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'),
    ]
    

    新建主题。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 %}
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Mauricio Cortazar    7 年前

    问题在您的表单中,只需删除操作:

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