sen
sen

Reputation: 75

Django get data from get method and pass to post method

I am trying to pass the data from get method to post method, so I can update my database data through a form. In below code, specifically I tried to use a class level variable "saved_objectID" to pass the editObjectID from get method to post method. But I always get blank values/no value.

Is there a way to implement this? Thank you in advance for the help

class EditDataView(ListView):
    model =TemporaryModel
    form_class = TemporaryForm
    template_name = 'frontend/editData.html'
    dict = { "EditData":"Edit Data Below"}
    saved_objectID = ''

    def get(self, request, *args, **kwargs):
        editObjectId = request.GET.get('editObjectId')
        editObjects = TemporaryModel.objects.get(pk=editObjectId)
        saved_objectID = editObjectId
        form = TemporaryForm(instance=editObjects)
        return render(request, 'frontend/editData.html', {'form': form,"dict":dict})

    def post(self, request, *args, **kwargs):
        form = TemporaryForm(request.POST, instance=TemporaryModel.objects.get(pk=self.saved_objectID))
        if form.is_valid():
            form.save()
            return render(request, 'frontend/editData.html', {'form': form,"dict":dict})

Upvotes: 1

Views: 2336

Answers (1)

atline
atline

Reputation: 31664

This depends on how you deploy your django application. I guess in your case, you http server use process to serve the user requests.

So, the two different user action get & post are in two different processes, although saved_objectID are both the class member of EditDataView, but the two EditDataView in two different python process. So, you cannot get the value.

Typically, don't make two different requests communicate by a variable in memory, even it can stay in the same process because you change http server deploy mode, you still can not get ride of other interfere(e.g. other user request's sequence).

For your scenario, why not just return the saved_objectID to user's brower using hidden variable? Or if you care about security, you can also use redis, store the saved_objectID as a value in redis and return the key to user's browser.

In a word, don't use variable in memory to communicate, you can assure nothing in a multi-process environment, find a standalone product if you really need it.

Upvotes: 2

Related Questions