예제 #1
0
def add_modify_trip(request, trip_id=None):
    """Add or modify an existing trip.
    
    If a trip id is specified, retreive it and edit it (save it if needed)
    If no trip id is specified, create a new new trip and process it.
    
    """
    if request.method == "POST":
        if trip_id:
            trip = get_object_or_404(Trip, id=trip_id, user=request.user)
            form_offer = EditTripOfferOptionsForm(data=request.POST, instance=trip.offer, prefix="offer")
            form_demand = EditTripDemandOptionsForm(data=request.POST, instance=trip.demand, prefix="demand")
        else:
            trip = Trip(user=request.user)
            form_offer = EditTripOfferOptionsForm(data=request.POST, prefix="offer")
            form_demand = EditTripDemandOptionsForm(data=request.POST, prefix="demand")

        form_trip = EditTripForm(data=request.POST, instance=trip)
        error = False
        if form_trip.is_valid():
            trip_type = int(form_trip["trip_type"].data)
            trip = form_trip.save(commit=False)

            if trip_type != Trip.DEMAND:
                if form_offer.is_valid():
                    trip.offer = form_offer.save()
                else:
                    error = True

            if trip_type != Trip.OFFER:
                if form_demand.is_valid():
                    trip.demand = form_demand.save()
                else:
                    error = True

            # if we have an offer, and a demand is already registred, delete it
            if trip_type == Trip.OFFER and trip.demand is not None:
                trip.demand.delete()
                trip.demand = None

            # if we have a demand, and an offer is already registred, delete it
            if trip_type == Trip.DEMAND and trip.offer is not None:
                trip.offer.delete()
                trip.offer = None
            if error == False:
                trip.save()
                if request.POST["return_trip"] == "true":
                    return HttpResponseRedirect(reverse("carpool:add_return_trip", args=[trip.id]))
                else:
                    return HttpResponseRedirect(reverse("carpool:show_trip_results", args=[trip.id]))

    # request.method = "GET"
    else:
        # request user preferences
        userprofiledata = model_to_dict(request.user.get_profile())

        form_trip = EditTripForm(initial=userprofiledata)
        form_offer = EditTripOfferOptionsForm(initial=userprofiledata, prefix="offer")
        form_demand = EditTripDemandOptionsForm(initial=userprofiledata, prefix="demand")

        if trip_id:
            trip = get_object_or_404(Trip, id=trip_id, user=request.user)
            form_trip = EditTripForm(instance=trip)
            if trip.offer:
                form_offer = EditTripOfferOptionsForm(instance=trip.offer, prefix="offer")
            if trip.demand:
                form_demand = EditTripDemandOptionsForm(instance=trip.demand, prefix="demand")

    response_dict = {
        "form_trip": form_trip,
        "form_offer_options": form_offer,
        "form_demand_options": form_demand,
        "default_center": settings.DEFAULT_MAP_CENTER_POINT,
        "default_zoom": settings.DEFAULT_MAP_CENTER_ZOOM,
    }

    template = loader.get_template("carpool/add_modify_trip.html")
    context = RequestContext(request, response_dict)
    return HttpResponse(template.render(context))
예제 #2
0
def add_trip_from_search(request):
    """Add a trip from a previous search (stored in session)
    
    """

    def _get_favorite_place(json, key):
        try:
            favorite_place_id = int(json.get(key).get("favoriteplace"))
            return FavoritePlace.objects.get(pk=favorite_place_id)
        except (ValueError, FavoritePlace.DoesNotExist):
            return None

    if request.method != "POST" or "trip_details" not in request.POST:
        return HttpResponseRedirect("carpool:add_trip")

    trip = Trip(user=request.user)

    try:
        json = simplejson.loads(request.POST["trip_details"])
        trip.trip_type = int(json.get("type"))
        trip.trip_radius = int(json.get("radius"))
        departure_favoriteplace = _get_favorite_place(json, "departure")
        if departure_favoriteplace:
            trip.departure_city = departure_favoriteplace.city
            trip.departure_address = departure_favoriteplace.address
            trip.departure_point = departure_favoriteplace.point
        else:
            trip.departure_city = json.get("departure").get("city")
            trip.departure_point = GEOSGeometry(json.get("departure").get("point"))
        arrival_favoriteplace = _get_favorite_place(json, "arrival")
        if arrival_favoriteplace:
            trip.arrival_city = arrival_favoriteplace.city
            trip.arrival_address = arrival_favoriteplace.address
            trip.arrival_point = arrival_favoriteplace.point
        else:
            trip.arrival_city = json.get("arrival").get("city")
            trip.arrival_point = GEOSGeometry(json.get("arrival").get("point"))
        trip.interval_min = min(abs(int(json.get("interval_min"))), MAX_INTERVAL)
        trip.interval_max = min(abs(int(json.get("interval_max"))), MAX_INTERVAL)
        trip.date = get_date(json.get("date"), FRENCH_DATE_INPUT_FORMATS)
        form = AddModifyTripOptionsForm(initial=model_to_dict(request.user.get_profile()), instance=trip)
    except:
        return HttpResponseRedirect(reverse("carpool:add_trip"))

    mpoints = MultiPoint([trip.departure_point, trip.arrival_point])
    response_dict = {
        "current_item": 10,
        "gmapkey": settings.GOOGLE_MAPS_API_KEY,
        "trip": trip,
        "form": form,
        "geometry": mpoints.envelope.wkt,
        "trip_from_search": True,
        "hours": range(24),
    }

    template = loader.get_template("carpool/add_modify_trip.html")
    context = RequestContext(request, response_dict)
    return HttpResponse(template.render(context))
예제 #3
0
def add_return_trip(request, trip_id):
    """Create a new back trip based on information of an existing trip
    
    """

    trip = get_object_or_404(Trip, pk=trip_id, user=request.user)
    new_trip = Trip(user=request.user)
    new_trip.name = _("%(trip_name)s - Return") % {"trip_name": trip.name}
    new_trip.trip_type = trip.trip_type
    new_trip.departure_city = trip.arrival_city
    new_trip.departure_address = trip.arrival_address
    new_trip.departure_point = trip.arrival_point
    new_trip.arrival_city = trip.departure_city
    new_trip.arrival_address = trip.departure_address
    new_trip.arrival_point = trip.departure_point
    new_trip.regular = trip.regular
    if new_trip.regular:
        new_trip.dows = trip.dows

    new_offer = None
    if trip.offer:
        new_offer = TripOffer()
        new_offer.checkpointlist = trip.offer.checkpointlist
        new_offer.checkpointlist.reverse()
        new_offer.radius = trip.offer.radius
        new_trip.offer = new_offer

    new_demand = None
    if trip.demand:
        new_demand = TripDemand()
        new_demand.radius = trip.demand.radius
        new_trip.demand = new_demand

    userprofiledata = model_to_dict(request.user.get_profile())

    form_trip = EditTripForm(initial=userprofiledata, instance=new_trip)
    form_offer = EditTripOfferOptionsForm(initial=userprofiledata, instance=new_offer, prefix="offer")
    form_demand = EditTripDemandOptionsForm(initial=userprofiledata, instance=new_demand, prefix="demand")

    points = [cp["point"] for cp in trip.offer.checkpointlist] if trip.offer else []
    points.append(trip.departure_point)
    points.append(trip.arrival_point)
    mpoints = MultiPoint(points)

    response_dict = {
        "form_trip": form_trip,
        "form_offer_options": form_offer,
        "form_demand_options": form_demand,
        "default_center": settings.DEFAULT_MAP_CENTER_POINT,
        "default_zoom": settings.DEFAULT_MAP_CENTER_ZOOM,
        "return_trip": True,
    }

    template = loader.get_template("carpool/add_modify_trip.html")
    context = RequestContext(request, response_dict)
    return HttpResponse(template.render(context))
예제 #4
0
    def _add_or_edit_trip(self, user, post_data, trip_id=None,
            formfactory={'trip'      : EditTripForm,
                         'tripoffer' : EditTripOfferOptionsForm,
                         'tripdemand': EditTripDemandOptionsForm}):
        """Add or edit a trip.
        
        If a trip id is specified, retreive it and edit it (save it if needed)
        If no trip id is specified, create a new new trip and process it.

        :post_data: can be in the form - or _ for offer and demand forms.
                    but it needs to be prefixed by offer or demand.
        """

        # XXX do not touch to these prefix, they are used in many places as hard values
        offer_prefix = "offer"
        demand_prefix = "demand"
        models_data = self._format_dict2model(post_data, offer_prefix, demand_prefix)

        trip_form = formfactory['trip']
        tripoffer_form = formfactory['tripoffer']
        tripdemand_form = formfactory['tripdemand']
        
        if trip_id:
            trip = Trip.objects.get(id=trip_id, user=user)
            form_offer = tripoffer_form(data=models_data, instance=trip.offer, prefix=offer_prefix)
            form_demand = tripdemand_form(data=models_data, instance=trip.demand, prefix=demand_prefix)
        else:
            trip = Trip(user=user)
            form_offer = tripoffer_form(data=models_data, prefix=offer_prefix)
            form_demand = tripdemand_form(data=models_data, prefix=demand_prefix)

        form_trip = trip_form(data=models_data, instance=trip)

        
        error = False
        if form_trip.is_valid():
            trip_type = int(form_trip['trip_type'].data)
            trip = form_trip.save(commit=False)
            
            if trip_type != self.TRIPDEMAND : 
                #### FIX: we should not need to provide "steps" for updates
                if form_offer.is_valid():
                    offer = form_offer.save(commit=False)
                    offer.steps = simplejson.loads(form_offer.cleaned_data['steps'])
                    offer.save()
                    trip.offer = offer
                else:
                    error = form_offer.errors
                
            if trip_type != self.TRIPOFFER:
                if form_demand.is_valid():
                    trip.demand = form_demand.save()
                else:
                    error = True
            if not error:
                # if we have an offer, and a demand is already registred, delete it 
                if trip_type == self.TRIPOFFER and trip.demand is not None: 
                    trip.demand.delete()
                    trip.demand = None 
                
                # if we have a demand, and an offer is already registred, delete it   
                if trip_type == self.TRIPDEMAND and trip.offer is not None: 
                    trip.offer.delete()
                    trip.offer = None

                trip.save()
        else:
            error = True
        return {
            'form_demand': form_demand,
            'form_offer': form_offer,
            'form_trip': form_trip,
            'trip': trip,
            'error': error,
        }
예제 #5
0
    def _add_or_edit_trip(
        self,
        user,
        post_data,
        trip_id=None,
        formfactory={
            'trip': EditTripForm,
            'tripoffer': EditTripOfferOptionsForm,
            'tripdemand': EditTripDemandOptionsForm
        }):
        """Add or edit a trip.
        
        If a trip id is specified, retreive it and edit it (save it if needed)
        If no trip id is specified, create a new new trip and process it.

        :post_data: can be in the form - or _ for offer and demand forms.
                    but it needs to be prefixed by offer or demand.
        """

        # XXX do not touch to these prefix, they are used in many places as hard values
        offer_prefix = "offer"
        demand_prefix = "demand"
        models_data = self._format_dict2model(post_data, offer_prefix,
                                              demand_prefix)

        trip_form = formfactory['trip']
        tripoffer_form = formfactory['tripoffer']
        tripdemand_form = formfactory['tripdemand']

        if trip_id:
            trip = Trip.objects.get(id=trip_id, user=user)
            form_offer = tripoffer_form(data=models_data,
                                        instance=trip.offer,
                                        prefix=offer_prefix)
            form_demand = tripdemand_form(data=models_data,
                                          instance=trip.demand,
                                          prefix=demand_prefix)
        else:
            trip = Trip(user=user)
            form_offer = tripoffer_form(data=models_data, prefix=offer_prefix)
            form_demand = tripdemand_form(data=models_data,
                                          prefix=demand_prefix)

        form_trip = trip_form(data=models_data, instance=trip)

        error = False
        if form_trip.is_valid():
            trip_type = int(form_trip['trip_type'].data)
            trip = form_trip.save(commit=False)

            if trip_type != self.TRIPDEMAND:
                #### FIX: we should not need to provide "steps" for updates
                if form_offer.is_valid():
                    offer = form_offer.save(commit=False)
                    offer.steps = simplejson.loads(
                        form_offer.cleaned_data['steps'])
                    offer.save()
                    trip.offer = offer
                else:
                    error = form_offer.errors

            if trip_type != self.TRIPOFFER:
                if form_demand.is_valid():
                    trip.demand = form_demand.save()
                else:
                    error = True
            if not error:
                # if we have an offer, and a demand is already registred, delete it
                if trip_type == self.TRIPOFFER and trip.demand is not None:
                    trip.demand.delete()
                    trip.demand = None

                # if we have a demand, and an offer is already registred, delete it
                if trip_type == self.TRIPDEMAND and trip.offer is not None:
                    trip.offer.delete()
                    trip.offer = None

                trip.save()
        else:
            error = True
        return {
            'form_demand': form_demand,
            'form_offer': form_offer,
            'form_trip': form_trip,
            'trip': trip,
            'error': error,
        }
예제 #6
0
def add_modify_trip(request, trip_id=None):
    """Add or modify an existing trip.
    
    If a trip id is specified, retreive it and edit it (save it if needed)
    If no trip id is specified, create a new new trip and process it.
    
    """
    if request.method == 'POST':
        if trip_id:
            trip = get_object_or_404(Trip, id=trip_id, user=request.user)
            form_offer = EditTripOfferOptionsForm(data=request.POST, 
                instance=trip.offer, prefix="offer")
            form_demand = EditTripDemandOptionsForm(data=request.POST, 
                instance=trip.demand, prefix="demand")
        else:
            trip = Trip(user=request.user)
            form_offer = EditTripOfferOptionsForm(data=request.POST, 
                prefix="offer")
            form_demand = EditTripDemandOptionsForm(data=request.POST,
                prefix="demand")
 
        form_trip = EditTripForm(data=request.POST, instance=trip)
        error = False
        if form_trip.is_valid():
            trip_type = int(form_trip['trip_type'].data)
            trip = form_trip.save(commit=False)
            
            if trip_type != Trip.DEMAND : 
                if form_offer.is_valid():
                    trip.offer = form_offer.save()
                else:
                    error = True
                
            if trip_type != Trip.OFFER:
                if form_demand.is_valid():
                    trip.demand = form_demand.save()
                else:
                    error = True
            
            # if we have an offer, and a demand is already registred, delete it 
            if trip_type == Trip.OFFER and trip.demand is not None: 
                trip.demand.delete()
                trip.demand = None 
            
            # if we have a demand, and an offer is already registred, delete it   
            if trip_type == Trip.DEMAND and trip.offer is not None: 
                trip.offer.delete()
                trip.offer = None 
            if error ==False:
                trip.save()
                if request.POST['return_trip'] == 'true':
                    return HttpResponseRedirect(reverse('carpool:add_return_trip', args=[trip.id]))
                else:
                    return HttpResponseRedirect(reverse('carpool:show_trip_results', args=[trip.id]))
    
    # request.method = "GET"
    else:
        # request user preferences
        userprofiledata = model_to_dict(request.user.get_profile())

        form_trip = EditTripForm(initial=userprofiledata)
        form_offer = EditTripOfferOptionsForm(initial=userprofiledata, prefix="offer")
        form_demand = EditTripDemandOptionsForm(initial=userprofiledata, prefix="demand")
        
        if trip_id:
            trip = get_object_or_404(Trip,id=trip_id, user=request.user)
            form_trip = EditTripForm(instance=trip)
            if trip.offer:
                form_offer = EditTripOfferOptionsForm(instance=trip.offer, 
                    prefix="offer")
            if trip.demand:
                form_demand = EditTripDemandOptionsForm(instance=trip.demand, 
                    prefix="demand")
    
    response_dict = {
        'form_trip': form_trip,
        'form_offer_options': form_offer,
        'form_demand_options': form_demand,
        'default_center': settings.DEFAULT_MAP_CENTER_POINT,
        'default_zoom': settings.DEFAULT_MAP_CENTER_ZOOM     
    }

    template = loader.get_template('carpool/add_modify_trip.html')
    context = RequestContext(request, response_dict)
    return HttpResponse(template.render(context))
예제 #7
0
def add_return_trip(request, trip_id):
    """Create a new back trip based on information of an existing trip
    
    """                   
                    
    trip = get_object_or_404(Trip, pk=trip_id, user=request.user)
    new_trip = Trip(user=request.user)
    new_trip.name = _('%(trip_name)s - Return') % {'trip_name': trip.name}
    new_trip.trip_type = trip.trip_type
    new_trip.departure_city = trip.arrival_city
    new_trip.departure_address = trip.arrival_address
    new_trip.departure_point = trip.arrival_point
    new_trip.arrival_city = trip.departure_city
    new_trip.arrival_address = trip.departure_address
    new_trip.arrival_point = trip.departure_point
    new_trip.regular = trip.regular
    if new_trip.regular:
        new_trip.dows = trip.dows

    new_offer = None
    if trip.offer:
        new_offer = TripOffer()
        new_offer.checkpointlist = trip.offer.checkpointlist
        new_offer.checkpointlist.reverse()
        new_offer.radius = trip.offer.radius
        new_trip.offer = new_offer

    new_demand = None
    if trip.demand:
        new_demand = TripDemand()
        new_demand.radius = trip.demand.radius
        new_trip.demand = new_demand

    userprofiledata = model_to_dict(request.user.get_profile())
        
    form_trip = EditTripForm(initial=userprofiledata, instance=new_trip)
    form_offer = EditTripOfferOptionsForm(initial=userprofiledata, 
        instance=new_offer, prefix='offer')
    form_demand = EditTripDemandOptionsForm(initial=userprofiledata, 
        instance=new_demand, prefix='demand')

    points = [cp['point'] for cp in trip.offer.checkpointlist] if trip.offer else []
    points.append(trip.departure_point)
    points.append(trip.arrival_point)
    mpoints = MultiPoint(points)    

    response_dict = {
        'form_trip': form_trip,
        'form_offer_options': form_offer,
        'form_demand_options': form_demand,
        'default_center': settings.DEFAULT_MAP_CENTER_POINT,
        'default_zoom': settings.DEFAULT_MAP_CENTER_ZOOM,
        'return_trip': True,
    }

    template = loader.get_template('carpool/add_modify_trip.html')
    context = RequestContext(request, response_dict)
    return HttpResponse(template.render(context))
예제 #8
0
def add_trip_from_search(request):
    """Add a trip from a previous search (stored in session)
    
    """
    def _get_favorite_place(json, key):
        try:
            favorite_place_id = int(json.get(key).get('favoriteplace'))
            return FavoritePlace.objects.get(pk=favorite_place_id)
        except (ValueError, FavoritePlace.DoesNotExist):
            return None

    if request.method != 'POST' or 'trip_details' not in request.POST:
        return HttpResponseRedirect('carpool:add_trip')

    trip = Trip(user=request.user)

    try:
        json = simplejson.loads(request.POST['trip_details'])
        trip.trip_type = int(json.get('type'))
        trip.trip_radius = int(json.get('radius'))
        departure_favoriteplace = _get_favorite_place(json, 'departure')
        if departure_favoriteplace:
            trip.departure_city = departure_favoriteplace.city
            trip.departure_address = departure_favoriteplace.address
            trip.departure_point = departure_favoriteplace.point
        else:
            trip.departure_city = json.get('departure').get('city')
            trip.departure_point = GEOSGeometry(json.get('departure').get('point'))
        arrival_favoriteplace = _get_favorite_place(json, 'arrival')
        if arrival_favoriteplace:
            trip.arrival_city = arrival_favoriteplace.city
            trip.arrival_address = arrival_favoriteplace.address
            trip.arrival_point = arrival_favoriteplace.point
        else:
            trip.arrival_city = json.get('arrival').get('city')
            trip.arrival_point = GEOSGeometry(json.get('arrival').get('point'))
        trip.interval_min = min(abs(int(json.get('interval_min'))), MAX_INTERVAL)
        trip.interval_max = min(abs(int(json.get('interval_max'))), MAX_INTERVAL)
        trip.date = get_date(json.get('date'), FRENCH_DATE_INPUT_FORMATS)
        form = AddModifyTripOptionsForm(initial=model_to_dict(request.user.get_profile()), instance=trip)
    except:
        return HttpResponseRedirect(reverse('carpool:add_trip'))

    mpoints = MultiPoint([trip.departure_point, trip.arrival_point])
    response_dict = {
        'current_item': 10,
        'gmapkey': settings.GOOGLE_MAPS_API_KEY,
        'trip': trip,
        'form': form,
        'geometry': mpoints.envelope.wkt,
        'trip_from_search': True,
        'hours': range(24),
    }

    template = loader.get_template('carpool/add_modify_trip.html')
    context = RequestContext(request, response_dict)
    return HttpResponse(template.render(context))
예제 #9
0
 index += 1
 try:
     json = simplejson.loads(line)
     trip_type = random.choice([0, 1, 2])
     user = User.objects.get(pk=random.choice(USER_CHOICE))
     regular = random.choice([True, False])
     departure_city = decode_htmlentities(
         smart_unicode(json.get('departure_name')[0]))
     arrival_city = decode_htmlentities(
         smart_unicode(json.get('arrival_name')[0]))
     print departure_city, arrival_city, trip_type, user.username, regular
     trip = Trip(
         name=u"%s - %s" % (departure_city, arrival_city),
         user=user,
         departure_city=departure_city,
         departure_point=GEOSGeometry(json.get('departure_point')[0]),
         arrival_city=arrival_city,
         arrival_point=GEOSGeometry(json.get('arrival_point')[0]),
         regular=regular,
     )
     if not regular:
         trip.date = today
         trip.interval_min = random.randint(0, 6)
         trip.interval_max = random.randint(0, 6)
     else:
         trip.dows = [
             dow for dow in range(0, 7) if random.random() < 0.5
         ]
         if not trip.dows:
             trip.dows = [1]
     if trip_type != Trip.OFFER:
예제 #10
0
 index = 0
 for line in route_file:
     index += 1
     try:
         json = simplejson.loads(line)
         trip_type = random.choice([0, 1, 2])
         user = User.objects.get(pk=random.choice(USER_CHOICE))
         regular = random.choice([True, False])
         departure_city = decode_htmlentities(smart_unicode(json.get('departure_name')[0]))
         arrival_city = decode_htmlentities(smart_unicode(json.get('arrival_name')[0]))
         print departure_city, arrival_city, trip_type, user.username, regular
         trip = Trip(
             name=u"%s - %s" % (departure_city, arrival_city),
             user=user,
             departure_city=departure_city,
             departure_point=GEOSGeometry(json.get('departure_point')[0]),
             arrival_city=arrival_city,
             arrival_point=GEOSGeometry(json.get('arrival_point')[0]),
             regular=regular,
         )
         if not regular:
             trip.date = today
             trip.interval_min = random.randint(0, 6)
             trip.interval_max = random.randint(0, 6)
         else:
             trip.dows = [dow for dow in range(0, 7) if random.random() < 0.5]
             if not trip.dows:
                 trip.dows = [1]
         if trip_type != Trip.OFFER:
             demand = TripDemand(
                 radius=random.choice(DEMAND_RADIUS_CHOICE)