[Answered ]-How do I populate my form with the data sent by a user after a GET request in Django?

1👍

You can make a form without the extra logic for departure_airlport and arrival_airport, so simply:

class FlightSearchForm(forms.Form):
    departure_airport = forms.CharField(max_length=100)
    arrival_airport = forms.CharField(max_length=100)
    # no __init__

Then you can use the data as initial=… [Django-doc] data:

def index(request):
    if not request.GET:
        form = FlightSearchForm()
    else:
        arr = request.GET.get('arrival_airport')
        dep = request.GET.get('departure_airport')
        form = FlightSearchForm(initial={'departure_airport': dep,'arrival_airport': arr})
    return render(request, 'app1/index.html', {'form': form})

another option is to pass request.GET directly as data into the form:

def index(request):
    if not request.GET:
        form = FlightSearchForm()
    else:
        form = FlightSearchForm(request.GET)
    return render(request, 'app1/index.html', {'form': form})

Leave a comment