Never, ever catch the base class Exception
unless you handle it properly (i.e. log the error message etc.). Why? Because that except
clause hides the real problems in your code and makes debugging a huge pain in the ass.
The request.POST
object only contains plain strings. While fld_birth_date
may be a date-formatted string, you can't filter a DateField
with a string object. You need an actual date
object to filter.
What you need to do is convert the string to a date object. E.g. if your date always follows the format dd-mm-YYYY
, you can do:
import datetime
date = datetime.datetime.strftime(request.POST.get('fld_birth_date'), '%d-%m-%Y').date()
On top of that, you use if q_name
and if q_birth_date
while neither are defined at all, both raising another exception.
The if request.method == 'POST'
part of your code should probably look like this:
if request.method == 'POST':
name = request.POST.get('fld_name', None)
birth_date_string = request.POST.get('fld_birth_date', '')
try:
birth_date = datetime.datetime.strftime(birth_date_string, '%d-%m-%Y').date()
except ValueError:
birth_date = None
search_results = UserProfile.objects.all()
if name:
search_results = search_results.filter(name__icontains=name.strip())
if birth_date:
search_results = search_results.filter(birth_date=birth_date)
Or if you want a result if either name or birth_date matches:
from django.db.models import Q
q = Q()
if name:
q |= Q(name__icontains=name.strip())
if birth_date:
q |= Q(birth_date=birth_date)
search_results = UserProfile.objects.filter(q)