html表单中不允许Django HTTP 405方法

2024-03-29 12:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django新手,我一直在尝试开发一个简单的网站,询问用户的电子邮件地址和身高。然后它将其保存在数据库中,并向用户发送电子邮件,并将他们重定向到一个页面,说明成功了。在

现在的问题是,每当我按“提交”时,都会收到一个http405方法不允许的错误。在

# urls.py
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    #url(r'^success/$', views.SuccessView.as_view(), name='success'),
]


# 表单.py 班级高度表(窗体.ModelForm)公司名称:

^{pr2}$


# views.py
class IndexView(generic.ListView):
    form_class = HeightForm
    template_name = 'heights/index.html'

    def get_queryset(self):
        return Height.objects.all()

class HeightFormView(View):
    form_class = HeightForm
    template_name = 'heights/success.html'

    def get(self, request):
        form = form_class(None)

    def post(self, request):
        print('a' * 1000)
        form = form_class(request.POST)

        if form.is_valid:
            email = form.cleaned_data['email']
            height = form.cleaned_data['height']

            form.save()

            return HttpResponseRedirect(template_name)

    #render(request, template_name, {'form': form})


# index.html
{% extends 'heights/base.html' %}

{% block body %}
    <h1>Collecting Heights</h1>
    <h3>Please fill the entries to get population statistics on height</h3>
    <form action="" method="post">
        {% csrf_token %}
        <input type="email" name="email" placeholder="Enter your email address" required="true"/><br />
        <input type="number" min="50" max="300" name="height" placeholder="Enter your height in cm" required="true" /><br /><br />
        <input type="submit" name="submit" />
    </form>

    <a href="#">Click to view all heights in database</a>
{% endblock body %}

代码甚至不能到达print('a' * 1000)行而不生成错误。Chrome只是转到This page isn't working页面并显示HTTP ERROR 405。在

我在google上搜索了这个错误,但没有发现anthing有用。感谢任何帮助

谢谢


Tags: namepyformviewindexemailrequesthtml
2条回答

您似乎没有为HeightFormView定义任何URL。表单由IndexView呈现并返回给它自己;该视图不允许使用POST方法。在

您需要为HeightFormView定义一个URL,并通过{% url %}标记在操作中引用它。在

为表单添加提交路径网址.py在行动中使用同样的方法。应该能正常工作。在

urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^saveForm/$', views.HeightFormView.as_view(), name='form'), ]

在html表单中

<form action="/saveForm" method="post">

相关问题 更多 >