New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev #3

Merged
merged 2 commits into from Dec 7, 2017
Jump to file or symbol
Failed to load files and symbols.
+44 −7
Diff settings

Always

Just for now

View
@@ -35,3 +35,27 @@ def validate_data(car):
errors['owners_name'] = "This field is required."
return errors if errors else None
def validate_year_filter(start_year, end_year):
errors = {}
if start_year:
try:
st_year = int(start_year)
if st_year > 2017:
errors['from'] = "Value must be lower than 2018 and higher than 1940."
except:
errors['from'] = "Must be a positive integer."
else:
errors['from'] = "This field is required"
if end_year:
try:
e_year = int(end_year)
if e_year > 2017:
errors['to'] = "Value must be lower than 2018 and higher than 1940."
except:
errors['to'] = "Must be a positive integer."
else:
errors['to'] = "This field is required"
return errors
View
@@ -2,7 +2,7 @@
from .models import Car
from django.http import HttpResponse, JsonResponse
from django.core import serializers
from .validate import validate_data
from .validate import validate_data, validate_year_filter
import json
@@ -49,11 +49,16 @@ def create(request):
def filter_by_year(request):
if request.method == "POST":
data = json.loads(request.body)
print(data)
year_from = data["from"]
year_to = data["to"]
cars = Car.objects.filter(year__range=[year_from, year_to])
response_data = {}
response_data["data"] = serializers.serialize('json', cars)
return JsonResponse(response_data)
errors = validate_year_filter(year_from, year_to)
if not errors:
cars = Car.objects.filter(year__range=[year_from, year_to])
response_data = {}
response_data["data"] = serializers.serialize('json', cars)
return JsonResponse(response_data)
else:
return JsonResponse(json.dumps(errors), status=400, safe=False)
else:
return render(request, "main/index.html")
View
@@ -40,6 +40,7 @@ function filter_by_year() {
url: '/cars/filter_by_year/',
data: JSON.stringify(_data),
contentType: 'application/json; charset=utf-8',
success: function (response) {
response_data = JSON.parse(response.data);
console.log(response_data);
@@ -53,8 +54,15 @@ function filter_by_year() {
response_data[i].fields.model + "</td> <td>" + response_data[i].fields.category + "</td> <td>" + response_data[i].fields.price + "</td> </tr>");
}
},
error: function (data) {
//TODO: handle errors
error: function (errors_response) {
errors = JSON.parse(errors_response.responseJSON);
for (var key in errors) {
// check if the property/key is defined in the object itself, not in parent
if (errors.hasOwnProperty(key)) {
$("#" + key + "_input").val(errors[key]);
}
}
}
});
}
ProTip! Use n and p to navigate between commits in a pull request.