0

我正在尝试在我的网站首页创建一个简单的订阅表单。我使用模型表单创建了视图(模型仅包含名称和电子邮件作为属性)。当我转到根地址 (GET) 时,它可以正常工作并加载表单。然后我用一些数据填充它,单击提交按钮(表单操作可以设置为''或'/',结果相同)并重定向到相同的根页面,但它不加载任何东西,页面保持空白。在控制台中,我可以看到它通过 POST 方法调用,但甚至没有打印视图函数的第一个打印。

有任何想法吗?我知道这一定很傻,但我花了一些时间在里面,还没有发现它可能是什么。

在 urls.py 中:

url(r'', FrontPage.as_view(template_name='rootsite/frontpage.html')),

在 rootsite/views.py

class FrontPage(TemplateView):
    '''
    Front (index) page of the app, so that users can subscribe to
    have create their own instance of the app
    '''

    template_name = 'rootsite/frontpage.html'

    def get_context_data(self, 
                         *args, 
                         **kwargs):

        c = {}
        c.update(csrf(self.request))
        print self.request.method
        if self.request.method is 'POST':
            print 'OK - POST IT IS, FINALLY'
            form = NewUsersForm(self.request.POST)
            print form.__dict__
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/' + '?thanks=1')
         else:
            form = NewUsersForm()

        return {'form':form}
4

2 回答 2

1

您不能从 get_context_data 中返回重定向 - 它仅用于上下文数据,因此得名。

您应该为此使用正确的表单视图,其中包括表单验证后重定向的方法。

于 2013-09-10T07:32:01.830 回答
0

您是否在模板中包含 csrf_token(根据此处的示例:http: //www.djangobook.com/en/2.0/chapter07.html)?

<form action="" method="post">
    <table>
        {{ form.as_table }}
    </table>
    {% csrf_token %}
    <input type="submit" value="Submit">
</form>

我可能是错的,但我认为 Django 不会接受没有 csrf 令牌的 POST 请求?

于 2013-09-10T01:57:54.103 回答