首页 > 解决方案 > 通过 GET 发送时发送到 django 表单的请求对象正常,但通过 POST 发送时为空

问题描述

我正在尝试将请求用户发送到 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 对象但得到相同的结果......

标签: pythondjangodjango-forms

解决方案


不需要req_ses参数和所有额外的工作来找到request.user,因为HttpRequest对象具有user属性。

这是您的代码,经过一些简化,有望解决问题:

表格.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)

视图.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)

推荐阅读