def index(request):
if len(request.GET) == 0:
form = FlightSearchForm()
else:
arr = request.GET.get('arrival_airport')
dep = request.GET.get('departure_airport')
form = FlightSearchForm({'departure_airport': dep,'arrival_airport': arr})
return render(request, 'app1/index.html', {'form': form})
What I want to do is create a form that would allow users to search for a flight, so I need them to use GET request. The problem is I don't know how to make their search appear in the fields after they go to their specific url (with all the details they searched for). It worked with a POST request in the past, but obviously I can't use it in this case.
class FlightSearchForm(forms.Form):
def __init__(self, *args, **kwargs):
self.departure_airport = kwargs.pop('departure_airport')
self.arrival_airport = kwargs.pop('arrival_airport')
super.__init__(*args, **kwargs)
departure_airport = forms.CharField(max_length=100)
arrival_airport = forms.CharField(max_length=100)
I tried something like that but it didn't help. Now it shouts that there is a keyerror, which doesn't exist. What can I do about this?
CodePudding user response:
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})