0

I am building an application where an API searches for some information you inputted into a form. When I click on refresh there is an annoying popup in Chrome asking to resent the information. After some time googeling I found out that you have to use HttpResponseRedirect to avoid this. Unfortunately, it kills all the variables and I cannot derive any of them. Additionally, I had to instantiate the local variables to avoid errors where putting then into the “context”, as the variables were not yet defined without pushing the “Submit” button in the form. The instantiation also will kill the variables. Also tried to use global variables, but then the data can be seen across users. Now I have no ideas left. It would be nice to retain the information in the variables.

Code:

def realestate(request):
    context = {}
    json = {}
    coordinates = {}
    pages = 0
    rent = 0
    address_save = ""
    radius_save = ""
    address = ""

    if request.method == 'POST':
        address = request.POST.get('address')
        radius = request.POST.get('radius')
        # call the api only if adress or radius changed
        if address != address_save or radius != radius_save:
            pageNumber = request.POST.get('pageNumber')
            # receive coordinates from goodle
            coordinates = googleGeoApi(address)
            # search real estate with coordinates from immoscout24
            json, pages = search_api(pageNumber, coordinates, radius)
            # calculate rent with search from immoscout24
            rent = calculateRent(coordinates, radius)
            address_save = address
            radius_save = radius
        return HttpResponseRedirect(request.path_info)

    context = {'json': json, 'coordinates': coordinates, 'pages': pages, "rent": rent, "address": address}
    return render(request=request, template_name='realestate/realestate.html', context = context)
stud3nt
  • 2,056
  • 1
  • 12
  • 21
DimiDev
  • 73
  • 1
  • 7

1 Answers1

0

You can add the parameters to a query string and append it to request.path_info before redirecting. Then, for clarity I would add:

elif request.method == 'GET':

and populate your context from the GET parameters. This is a little bit fiddly, but it will do what you are asking for.

Mark Bailey
  • 1,617
  • 1
  • 7
  • 13
  • found this post: https://stackoverflow.com/questions/1463489/how-do-i-pass-template-context-information-when-using-httpresponseredirect-in-dj It looks like I have to add variables to URL String and fetch them in the coding. Have to find out how to do this :( – DimiDev Dec 31 '19 at 11:31