Home > database >  Sharing context between get and post
Sharing context between get and post

Time:01-14

what is the correct way to share context between a get and post invocation in same view in Django without sending anything anything to client? Can I do something like below?

   class Req(TemplateView):
    @login_required
    def get(self, request, *args, **kwargs):
        recepient=self.kwargs['recepient']
        ftype=self.kwargs['type']
   

    @login_required
    def post(self, request, *args, **kwargs):
        recepient=self.kwargs['recepient']
        ftype=self.kwargs['type']
   

CodePudding user response:

Yes, you can share context between a GET and POST invocation in the same view in Django by using the self.kwargs dictionary to store the values of the recepient and ftype variables. The self.kwargs dictionary is available to both the GET and POST methods, so you can access it from both methods to get the values that were passed in.

However, it's important to note that the self.kwargs dictionary is only accessible within the same request cycle, so if you need to share context between different requests, you should use a different method such as storing the values in a session or database.

Also, you could use class-based-view's dispatch method instead of get and post methods. In dispatch method you can set context to self and access it in get and post methods.

CodePudding user response:

I would strongly recommend using sessions to accomplish this. You can set the session by doing something like this:

request.session['receipt'] = receipt

And anytime you wanted to reference the receipt, you can do this:

request.session.get('receipt')

You can read more about sessions here.

  • Related