Example #1
0
def cars_view(request):
    """A view for cars."""
    if request.method == 'POST':
        # POST creates a car
        try:
            data = json.loads(request.body)
        except ValueError:
            return HttpResponseBadRequest('Not valid JSON!')

        form = CarForm(data)

        if form.is_valid():
            car = form.save()

            # Return a 201 CREATED response
            response = HttpResponse(status=201)
            response['Location'] = '/cars/' + str(car.id)

            return response
        else:
            return HttpResponseBadRequest('Invalid data!')
    elif request.method == 'GET':
        # GET returns a list of objects
        cars = Car.objects.all()
        return render_to_response('cars.json', {'cars': cars},
                                  content_type='application/json')

    # Notify client of supported methods
    return HttpResponseNotAllowed(['GET', 'POST'])
Example #2
0
def add_new_car(request):
    if request.method == 'POST':
        form = CarForm(request.POST, request.FILES)
        if form.is_valid():
            car = form.save(commit=False)
            car.user = request.user
            car.save()
            location = os.path.join(BASE_DIR, 'media', 'user_uploads',
                                    '{}-{}'.format(request.user.id, request.user.username),
                                    '{}-{}'.format(car.pk, car.name), 'images')
            location_to_database = os.path.join('user_uploads',
                                                '{}-{}'.format(request.user.id, request.user.username),
                                                '{}-{}'.format(car.pk, car.name), 'images', )
            fs = FileSystemStorage(location=location)
            image = request.FILES.get('image', False)
            logo = request.FILES.get('logo', False)
            if image:
                fs.save(str(car.image), image)
                car.image = os.path.join(location_to_database, str(car.image))
                car.save()
            if logo:
                fs.save(str(car.logo), logo)
                car.logo = os.path.join(location_to_database, str(car.logo))
                car.save()
            return redirect('cars:cars_home')
    else:
        form = forms.CarForm()
    return redirect('cars:cars_home')
Example #3
0
 def get_queryset(self):
     queryset = super().get_queryset()
     self.form = CarForm(self.request.GET)
     if self.form.is_valid():
         filters = Car.get_filter(self.request.GET)
         return queryset.filter(filters)
     else:
         return queryset
Example #4
0
def car_home(request):
    """ Car home. """
    if request.POST:
        form = CarForm(request.POST)
        if form.clean:
            instance = form.save(commit=False)
            instance.save() 
    form = CarForm()
    return render_to_response('car_home.html', locals(), context_instance=RequestContext(request))
Example #5
0
def add_car(request):
    form = CarForm()
    if request.method == "POST":
        form = CarForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect("cars:index")
    return {
       "form": form
    }
Example #6
0
def carview(request):  
    if request.method == "POST":  
        form = CarForm(request.POST)  
        if form.is_valid():  
            try:  
                form.save()  
                return redirect('/show')  
            except:  
                pass  
    else:  
        form = CarForm
    return render(request,'index.html',{'form':form})  
Example #7
0
def edit(request, id):
    p = get_object_or_404(Car, pk=id)
    if request.method == "POST":
        form = CarForm(request.POST)

        if form.is_valid():
            p.MPG = form.cleaned_data['MPG']
            p.HP = form.cleaned_data['HP']
            p.BODYTYPE = form.cleaned_data['BODYTYPE']
            p.TRANSMISSION = form.cleaned_data['TRANSMISSION']
            p.NUM_GEARS = form.cleaned_data['NUM_GEARS']
            p.save()
            return http.HttpResponseRedirect('/cars/')
    else:
        form = CarForm(instance=p)
    context = Context({'title': 'Edit Item', 'form': form, 'car': p })
    return render_to_response('cars/edit.html', context, context_instance=RequestContext(request))
Example #8
0
def car_details(request, car_id):
    car = Car.objects.filter(pk=car_id, user=request.user)
    form = CarForm(request.POST, request.FILES)
    car_fuel_fill_list = Fuel.objects.filter(car_id=car_id).order_by('-date')
    car_fill_form = FuelFillForm()
    json_serializer = serializers.get_serializer("json")()
    chart_dates = json_serializer.serialize(Fuel.objects.filter(car_id=car_id).order_by('date'), ensure_ascii=False)
    service_list = Service.objects.select_related().filter(car_id=car_id).order_by('-date')
    total_fuel_list = []
    total_km_list = []
    averages_list = []
    fuel_cost_list = []
    dates_list = []
    for fuel in car_fuel_fill_list:
        total_fuel_list.append(fuel.liters)
        total_km_list.append(fuel.kilometers)
        averages_list.append(round(fuel.liters/fuel.kilometers * 100, 2))
        fuel_cost_list.append(fuel.liters * float(fuel.fuel_price))
        dates_list.append(fuel.date)

    first_last_fuel_time_interval = max(dates_list) - min(dates_list)
    first_last_fuel_time_interval_months = first_last_fuel_time_interval.days / 31
    total_fuel = round(sum(total_fuel_list), 2)
    total_km = round(sum(total_km_list), 2)
    total_fuel_cost = round(sum(fuel_cost_list), 2)
    lowest_average = min(averages_list)
    highest_average = max(averages_list)
    month_average = round(total_fuel_cost / first_last_fuel_time_interval_months, 2)
    km_month_average = round(total_km / first_last_fuel_time_interval_months, 2)
    try:
        average_consumption = round(total_fuel / total_km * 100, 2)
    except ZeroDivisionError:
        average_consumption = 0

    try:
        last_service = service_list[0]
    except IndexError:
        last_service = ''

    context = {
        'car': car,
        'form': form,
        'car_fuel_fill_list': car_fuel_fill_list,
        'car_fill_form': car_fill_form,
        'chart_dates': chart_dates,
        'service_dictionary': get_services_as_dict(service_list)[0],
        'last_service': last_service,
        'average_consumption': average_consumption,
        'service_total_cost': get_services_as_dict(service_list)[1],
        'lowest_average': lowest_average,
        'highest_average': highest_average,
        'total_fuel_cost': total_fuel_cost,
        'month_average': month_average,
        'total_fuel': total_fuel,
        'total_km': total_km,
        'km_month_average': km_month_average,
    }
    return render(request, 'cars/car_details.html', context)
Example #9
0
def cars_home(request):
    user_cars = Car.objects.filter(user=request.user, sold=False)
    user_sold_cars = Car.objects.filter(user=request.user, sold=True)
    new_car_form = CarForm(request.POST)
    context = {
        'user_cars': user_cars,
        'form': new_car_form,
        'user_sold_cars': user_sold_cars
    }
    return render(request, 'cars/home.html', context)
Example #10
0
    def put(self, request):
        """updating a car through PUT METHOD
    Args:
        request : Httprequest
    Returns:
        HttpResponse
    """
        try:
            data = json.loads(request.body)
        except ValueError:
            return HttpResponseBadRequest('Not valid JSON!')

        get_id = Car.objects.get(id=data.get('id'))
        form = CarForm(data, instance=get_id)
        if form.is_valid():
            form.save()
            response = HttpResponse(status=200)
            return response
        else:
            return HttpResponseBadRequest('Invalid data!')
Example #11
0
    def post(self, request):
        """Adding a car POST method
       Args:
        request : Httprequest
      Returns:
        HttpResponse
      """
        try:
            data = json.loads(request.body)
        except ValueError:
            return HttpResponseBadRequest('Not valid JSON!')

        form = CarForm(data)

        if form.is_valid():
            car = form.save()
            response = HttpResponse(status=201)
            response['Location'] = '/cars/' + str(car.id)
            return response
        else:
            return HttpResponseBadRequest('Invalid data!')
Example #12
0
def car_details(request, pk):
    """Retrieve, update or delete a car details"""
    try:
        car = Car.objects.get(id=int(pk))
    except Car.DoesNotExist:
        return HttpResponse(status=404)
    
    if request.method == 'GET':
        # GET returns a car object with given id
        return render_to_response('car.json', {'car': car},
                                  content_type='application/json')
    elif request.method == 'DELETE':
        # DELETE a car object
        car.delete()
        return HttpResponse(status=204)
    elif request.method == 'PUT':
        # PUT updates the details of existing car
        try:
            data = json.loads(request.body)
        except ValueError:
            return HttpResponseBadRequest('Not valid JSON!')

        form = CarForm(data)

        if form.is_valid():
            car.make = data.get('make', car.make)
            car.model = data.get('model', car.model)
            car.year = data.get('year', car.year)
            car.save()

            # Return a 205 CREATED response
            response = HttpResponse(status=205)
            response['Location'] = '/cars/' + str(car.id)

            return response
        else:
            return HttpResponseBadRequest('Invalid data!')
        
    # Notify client of supported methods
    return HttpResponseNotAllowed(['GET', 'DELETE', 'PUT'])
Example #13
0
class CarListView(FormMixin, ListView):
    model = Car
    paginate_by = 15
    form_class = CarForm

    def get_queryset(self):
        queryset = super().get_queryset()
        self.form = CarForm(self.request.GET)
        if self.form.is_valid():
            filters = Car.get_filter(self.request.GET)
            return queryset.filter(filters)
        else:
            return queryset

    def get_context_data(self):
        context = super().get_context_data()
        context['form'] = self.form
        return context
Example #14
0
def skrot(request):
    if request.method=='POST':
        if 'findCarData' in request.POST:
            plade=request.POST.get('numField')
            stel=request.POST.get('stelField')
            print str(plade)+str(stel)
            if plade:
                data=getCarData.getCarDataByPlateOrStel(plate=plade)
                if data is not None:
                    num_data=data['Registreringsnr:']
                    stel_data=data['Stelnummer:']
                    art_data=data['Art:']
                    year_data=data[u'F\xf8rste Registreringsdato:']
                    brand_data=data[u'M\xe6rke:']
                    form=CarForm(initial={'plate':num_data, 'stelNum':stel_data,'art':art_data,'year':year_data, 'brand':brand_data})
                    return render_to_response('skrot.html', {'form':form, 'text': 'Du kan også indtaste bilens oplysninger manuelt her'}, context_instance=RequestContext(request))
                else: 
                    form=CarForm()
                    return render_to_response('skrot.html', {'form':form, 'text': 'Du kan også indtaste bilens oplysninger manuelt her','errorsText':'Kan ikke finde bilen med denne nummerplade'}, context_instance=RequestContext(request))  
            elif stel:
                data=getCarData.getCarDataByPlateOrStel(stel=stel)
                if data is not None:
                    num_data=data['Registreringsnr:']
                    stel_data=data['Stelnummer:']
                    art_data=data['Art:']
                    year_data=data[u'F\xf8rste Registreringsdato:']
                    brand_data=data[u'M\xe6rke:']
                    form=CarForm(initial={'plate':num_data, 'stelNum':stel_data,'art':art_data,'year':year_data, 'brand':brand_data})
                    return render_to_response('skrot.html', {'form':form, 'text': 'Du kan også indtaste bilens oplysninger manuelt her'}, context_instance=RequestContext(request))
                else: 
                    form=CarForm()
                    return render_to_response('skrot.html', {'form':form, 'text': 'Du kan også indtaste bilens oplysninger manuelt her','errorsText':'Kan ikke finde bilen med dette stelnummer'}, context_instance=RequestContext(request))   
            else:
                form=CarForm()
                return render_to_response('skrot.html', {'form':form, 'text': 'Du kan også indtaste bilens oplysninger manuelt her', 'errorsText':'Mangler at indtaste bilens nummerplade eller stelnummer'}, context_instance=RequestContext(request))   
                
                
                
#            html="<html><body>Lad vær med det. Det er forbudt.</body></html>"
#            return HttpResponse(html) 
        else:
            form=CarForm(request.POST,request.FILES )
            if form.is_valid():
                d=form.cleaned_data['duration']
                now = datetime.now() #datetime.now().strftime('%y-%m-%d %H:%M')
                end=now+timedelta(days=int(d))
                
                car=models.Car(plate=form.cleaned_data['plate'], year=form.cleaned_data['year'], brand=form.cleaned_data['brand'],
                               address=form.cleaned_data['address'],  city=form.cleaned_data['city'],pickup=form.cleaned_data['pickup'], email=form.cleaned_data['email'],
                               tlf=form.cleaned_data['tlf'], start_time=now, end_time=end, picture=form.cleaned_data['picture'], )         
                car.save()
    #            car.picture.save(car.plate,form.cleaned_data['picture'],save=True )  
                aos=[]
                for g in request.POST.getlist('bid_area'):
                    ar=Area.objects.get(pk=g)
                    bid_area_to_car=BidArea(car=car,area=ar)
                    bid_area_to_car.save()
                    ao_from_one_area=AO.objects.filter(area=ar)
                    aos.append( ao_from_one_area)
                new_car_email(car,aos)
                             
                return render_to_response('skrot.html', {'form':form,'text':'Du har nu registreret din bil i vores database, og den er nu klar til at blive budt på.'},context_instance=RequestContext(request))
            else:
                return render_to_response('skrot.html', {'form':form, 'text':"Forkert indtastning, indtast bilens oplysninger igen"}, context_instance=RequestContext(request))
    else:
        form=CarForm() 
        return render_to_response('skrot.html', {'form':form, 'text': 'Du kan også indtaste bilens oplysninger manuelt her'}, context_instance=RequestContext(request))