簡體   English   中英

請求 object 發送到 django 表單通過 GET 發送時正常,但通過 POST 發送時為空

[英]Request object sent to django form ok when sent via GET but empty when sent via POST

I'm trying to send the request user to a Django form, the thing is, when I sent the object trough GET metho, the Django form receives it fine, but when I do it trough POST method, the request object it's always empty,這是代碼:

***************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 有 object,通過 POST 它說 req_ses 它是 None .....知道為什么嗎??我也嘗試發送 user_rec object 但得到了相同的結果....

不需要req_ses參數和您為查找request.user所做的所有額外工作,因為HttpRequest對象具有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)

視圖.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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM