Permalink
Browse files

Merge pull request #3 from BohdanKaminskyi/dev

Dev
  • Loading branch information...
BohdanKaminskyi committed Dec 7, 2017
2 parents ca7fa98 + dcdc32a commit 8d290b05453dc0dde5861e5998e22a10c41f0006
Showing with 44 additions and 7 deletions.
  1. +24 −0 cars/validate.py
  2. +10 −5 cars/views.py
  3. +10 −2 static/js/cars.js
@@ -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
@@ -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")
@@ -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]);
}
}
}
});
}

0 comments on commit 8d290b0

Please sign in to comment.