通过GET发送时,请求对象以ok格式发送到django形式,但通过POST发送时为空

时间:2019-09-28 18:18:13

标签: python django django-forms

我正在尝试将请求用户发送到Django表单,事实是,当我通过GET方法发送对象时,Django表单可以很好地接收它,但是当我通过POST方法执行该操作时,请求对象就是始终为空,这是代码:

*************** Views.py

class CreateRec(BaseView):

    template_name = 'test/rec.html'


    def get(self, request, **kwargs):
        rec_form = RecForm(req_ses = request)
        return render(request, self.template_name,{
            'rec_form': rec_form, 'f_new': True,
        })

    def post(self, request, **kwargs):
        user_rec = User.objects.get(username = request)
        profile = profile_models.RecProfile.objects.get(cnxuser = user_rec)
        form = RecForm(request.POST, request.FILES, req_ses = request)
        return render(request, self.template_name,{
            'rec_form': rec_form, 'f_new': True,
        })

*********** Form.py文件的片段:

class RecForm(forms.ModelForm):

    def __init__(self, req_ses = None, *args, **kwargs):
        super(RecForm, self).__init__(*args, **kwargs)
        self.req_ses = kwargs.pop('req_ses', None)
        user_rec = User.objects.get(username = req_ses.user)
        profile = profile_models.RecProfile.objects.get(cnxuser = user_rec)

通过GET,req_ses通过POST获得了对象,这说req_ses它为None .....为什么要??,我也尝试发送user_rec对象,但是得到了相同的结果。...

1 个答案:

答案 0 :(得分:1)

由于HttpRequest对象具有req_ses属性,因此不需要request.user参数以及查找user所做的所有额外工作。

这是您的代码,其中进行了一些简化,有望 解决该问题:

forms.py:

class RecForm(forms.ModelForm):    
    def __init__(self, *args, user=None, **kwargs):
        instance = profile_models.RecProfile.objects.get(cnxuser=user) 
        super(RecForm, self).__init__(*args, instance=instance, **kwargs)

views.py:

class CreateRec(BaseView):
    template_name = 'test/rec.html' 

    def get(self, request, **kwargs):
        rec_form = RecForm(user=request.user)
        return render(request, self.template_name,{
            'rec_form': rec_form, 'f_new': True,
        })

    def post(self, request, **kwargs):
        form = RecForm(request.POST, request.FILES, user=request.user)
        return render(request, self.template_name,{
            'rec_form': rec_form, 'f_new': True,
        })

更新

class RecForm(forms.ModelForm):    
    def __init__(self, *args, user=None, **kwargs):
        print('args: {}'.format(args))
        print('kwargs: {}'.format(kwargs))
        print('user: {}'.format(user))
        instance = profile_models.RecProfile.objects.get(cnxuser=user) 
        super(RecForm, self).__init__(*args, instance=instance, **kwargs)