lundi 28 décembre 2020

Trying to query database if user inputted city and state is there and redirect if True or False in Django

I have a sorting page that the visitor to my website enters in a city and state where they want to live. I need to check against out database if we have any results in or near that city. Below is my code.

def address(request):
    if request.method == 'POST':
        form = CityStateForm(request.POST)
        if form.is_valid():
            obj = Location_Targeting()
            city = request.POST.get("city")
            state = request.POST.get("state")
            homeAvailable = Home.objects.get(city = city, state=state)
            obj.city = form.cleaned_data["city"]
            obj.state = form.cleaned_data["state"]
            obj.save()
            return render(request, 'app/success.html')
        else:
            obj = Location_Targeting()
            obj.city = form.cleaned_data["city"]
            obj.state = form.cleaned_data["state"]
            obj.save()
            return render(request, 'app/failed.html')

    return render(request, 'GMH_app/address.html')

I want to save the form to my database in its own table which it should, but doesn't do. Then I want it to query the Home table in my database and look up the city and state and if there are homes in the city or surrounding area it redirects to a success page otherwise it redirects to a failure page.

In my debugger it shows the correct kwargs but returns a does not exist but I know it does. Also it seems to be case sensitive which wont be user friendly.

I know this probably seems like a lot but I have tried a lot of different things including the documentation and the above is as far as I've gotten. It may be that the state is a tuple ("1", "Alabama") etc. that may need to be unpacked? It shows the key number in the state column for the table it gets in the debugger. "1" instead of "Alabama". Would this throw it off? It wont save the state it just gives a Keyerror 'state'.

Any help is greatly appreciated. Thanks in advance. Hopefully I'm on the right track.




Aucun commentaire:

Enregistrer un commentaire