jsanchezs
jsanchezs

Reputation: 2070

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, here's the code :

***************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,
        })

***********The fragment of the Form.py file:

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)

Via GET, req_ses has the object , via POST It's says req_ses it's None.....any idea why ??, I tried to send the user_rec object too but got the same result....

Upvotes: 0

Views: 46

Answers (1)

Lord Elrond
Lord Elrond

Reputation: 16062

There is no need for the req_ses argument and all that extra work you do to find the request.user, since HttpRequest objects have the user attribute.

Here is your code, with some simplifications that will hopefully fix the problem:

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,
        })

Update

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)

Upvotes: 1

Related Questions