Django表单数据在帖子要求登录时丢失 [英] Django form data lost on making login required on post

查看:39
本文介绍了Django表单数据在帖子要求登录时丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我想要以下行为:

In my app, I want the following behaviour:

  1. 用户转到联系表格网址
  2. 用户填写联系表格
  3. (a)如果用户已登录,请验证并提交表单
  4. (b)如果用户未登录,请重定向到登录表单以进行登录,然后如果验证了用户凭据,则提交表单.

在我的 views.py 中,我有:

@method_decorator(login_required, name='post')
class ContactView(FormView):
    template_name = 'extras/contact.html'
    form_class = ContactForm

def post(self, request, *args, **kwargs):
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    if form.is_valid():
        return self.form_valid(form, **kwargs)
    else:
        return self.form_invalid(form, **kwargs)

def form_valid(self, form):
    instance = form.instance
    instance.request_user = self.request.user
    instance.save()
    messages.success(self.request, "Thank you for contacting us! We will reach you soon.")
    return super().form_valid(form)

def get_success_url(self):
    return reverse('main_home')

包括发布方法的想法来自于 SO答案

The idea of including a post method was taken from this SO Answer

这不起作用.用户将被重定向到登录表单,已登录,但是在丢失重定向之前显示空白表单并输入信息.

This does not work. The user is being redirected to login form, logged in, but displays a blank form and entered information before redirection is lost.

任何提示如何解决此问题?

推荐答案

将发布请求重定向到登录页面时,您将丢失发布数据.因此,您还应该重定向GET请求,以便用户在填写联系表之前登录.您可以通过装饰 dispatch 方法来实现.

When you redirect a post request to the login page, you’ll lose the post data. Therefore you should redirect GET requests as well, so that the user logs in before they fill out the contact form. You can do this by decorating the dispatch method.

@method_decorator(login_required, name='dispatch')
class ContactView(FormView):

这篇关于Django表单数据在帖子要求登录时丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆