L
L
Ladn02021-05-01 13:33:42
Django
Ladn0, 2021-05-01 13:33:42

Pass random value from get method to post method Django?

Let's say I have a view that inherits from the View class

class SomeVeiwClass(View):
    def get_random_number(self):
        return random.randint(1, 100)

    def get(self, request):
        context = {
            'some_number': self.get_random_number()
        }
        return render(request, 'some_template.html', context)

    def post(self, request):
         context = {
             'some_number': self.get_random_number()
         }
         return render(request, 'some_template.html', context)

The fact is that in this way I call the function every time, which means I get different numbers, so the question is how to make it so that once the random number received can be used in the post method, I tried to create an instance of the SomeViewClass class (the same class) and give it the result of calling the get_random_number method , but then I get
TypeError: get_random_number() missing 1 required positional argument: 'self'
though I call in the same class. I tried to pass a variable through a hidden input in html, but then it can be changed, and I need to make sure that the user cannot influence it in any way. I know that you can just write the result of calling the get_random_number method through shelve to some file when calling the get method, and then read from the same file when calling the post method, but I doubt the speed of such an operation :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-05-01
@Ladn0

In the get method, store the random value in the session, and in the post, retrieve it from it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question