I do not understand why I cannot define a default value for a get parameter even after reading the document about QueryDict. This is what I have:
def find_users(request):
selected_zipcode = request.GET.get('zipcode', 75000)
selected_service = request.GET.get('service', 1)
# raise Exception(request.GET)
users = User.objects.filter(
Q(zipcode=selected_zipcode),
Q(proposals__pk=selected_service)
)
return render(
request,
'users.html', {users
'users': pet_sitters,
})
I can get my parameter if set in my url but if I do not define a zipcode parameter, i do not get 75000 as value. I only have 75000 if zipcode parameter does not exists.
CodePudding user response:
It is possible that you wrote the querystring as ?zipcode
, or as ?zipcode=
. In that case the key is set and maps on the empty string.
You can set another value in that case by implementing this as:
selected_zipcode = request.GET.get('zipcode', 75000) or 75000
This will in case the result of request.GET.get(…)
has truthiness False
, return the second operand so 75000
.
It might however be better to work with a form, and pass the request.GET
as data, so:
class MyForm(forms.Form):
zipcode = forms.IntegerField(initial=75000, required=False)
service = form.IntegerField(initial=1, required=False)
and work in the view with:
def find_users(request):
form = MyForm(request.GET)
if form.is_valid():
selected_zipcode = myform.cleaned_data['zipcode']
selected_service = myform.cleaned_data['service']
# …
# …