예제 #1
0
def create_data():
    user = User.objects.create_user(username='******',
                                    email='*****@*****.**',
                                    password='******')

    vehicle = Vehicle(make='Make', model='Model', reg_number='1234', user=user)
    vehicle.save()

    origin = Place(name='Origin')
    origin.save()

    destination = Place(name='Destination')
    destination.save()
예제 #2
0
 def setUp(self):
     place_origin = Place(name="my place origin")
     place_origin.save()
     place_destination = Place(name="my place destination")
     place_destination.save()
     place_new = Place(name="my new place")
     place_new.save()
     route = Route(place_origin=place_origin,
                   place_destination=place_destination)
     route.save()
     self.place_origin = place_origin
     self.place_destination = place_destination
     self.place_new = place_new
     self.route = route
예제 #3
0
    def handle(self, *args, **options):

        if len(args) <= 0:
            raise CommandError('please specify file name')

        if not os.path.exists(args[0]):
            raise CommandError("file %s doesn't exist" % args[0])

        with open(args[0], 'r') as f:
            result = json.load(f)

        for i in result:
            try:
                place = Place.objects.get(vendor_id=i['id'])
                if place.data == json.dumps(i):
                    print "place id #%s already exist... skipping" % i["id"]
                else:
                    place.data = json.dumps(i)
                    place.save()
                    print "place id #%s was update" % i["id"]
            except Place.DoesNotExist:
                place = Place()
                place.vendor_id = i["id"]
                place.data = json.dumps(i)
                place.save()
                print "place id #%s added" % i["id"]
예제 #4
0
 def create(self, validated_data):
     place = Place(name=validated_data['name'],
                   google_place_id=validated_data['google_place_id'],
                   owner=validated_data['owner'],
                   point=GEOSGeometry(
                       Point(validated_data['lon'], validated_data['lat'])))
     place.save()
     return place
예제 #5
0
파일: utils.py 프로젝트: pelid/star-burger
def get_coordinates(apikey, address):
    try:
        place = Place.objects.get(address=address)
    except ObjectDoesNotExist:
        lon, lat = fetch_coordinates(apikey, address)
        place = Place(address=address, lat=lat, lon=lon)
        place.save()
    return place.lon, place.lat
예제 #6
0
    def create(name, lat, lng):
        position = GeometryService.create_geometry(lat, lng)

        place = Place()
        place.name = name
        place.position = position
        place.save()

        return place
예제 #7
0
    def setUp(self):
        User.objects.create_user("segalle", email=None, password="******")
        User.objects.create_user("moshe", email=None, password="******")
        p = Place()
        p.vendor_id = 1000
        p.data = {
        "city": "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd", 
        "name": "\u05e9\u05d9\u05da \u05d2'\u05e8\u05d0\u05d7", 
        "district": "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd", 
        "phones": "02-5871923", 
        "notes": "", 
        "subdistrict": "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd", 
        "days": [
            "8:00-17:00", 
            "8:00-17:00", 
            "8:00-17:00", 
            "8:00-17:00", 
            "8:00-13:00", 
            "\u05e1\u05d2\u05d5\u05e8"
        ], 
        "address": "\u05de\u05e8\u05db\u05d6 \u05e8\u05e4\u05d5\u05d0\u05d9", 
        "owner": "\u05e2\u05d9\u05e8\u05d9\u05d9\u05ea \u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd", 
        "id": 1000
        }
        p.save()
        
        self.pm = Placemark()
        self.pm.place = p
        self.pm.city = "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd"
        self.pm.address = "\u05de\u05e8\u05db\u05d6 \u05e8\u05e4\u05d5\u05d0\u05d9"
        self.pm.lat = 31.15
        self.pm.lng = 32.16
        self.pm.save()

        self.pm1 = Placemark()
        self.pm1.place = p
        self.pm1.city = "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd"
        self.pm1.address = "\u05de\u05e8\u05db\u05d6 \u05e8\u05e4\u05d5\u05d0\u05d9"
        self.pm1.lat = 31.25
        self.pm1.lng = 32.26
        self.pm1.save()

        self.pm2 = Placemark()
        self.pm2.place = p
        self.pm2.city = "\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd"
        self.pm2.address = "\u05de\u05e8\u05db\u05d6 \u05e8\u05e4\u05d5\u05d0\u05d9"
        self.pm2.lat = 31.35
        self.pm2.lng = 32.36
        self.pm2.save()
예제 #8
0
def accept_place(modeladmin, request, queryset, accept_link=True):
    from places.google_places_helper import fetch_details_for_place_id
    # we listify the queryset since we're going to edit objects such that they won't appear
    # in the queryset anymore
    any_added = False
    for suggestion in list(queryset):
        place_id = suggestion.place_id
        try:
            p = Place.objects.get(place_id=place_id)
        except Place.DoesNotExist:
            any_added = True
            p = Place(place_id=place_id)

            r, photo_url, photo_attrib = fetch_details_for_place_id(place_id)
            if not r.get(
                    'rating'
            ):  # probably not meaningful place, or Google returned NOT_FOUND
                suggestion.processed = True
                suggestion.save()
                continue
            p.name = r['name']
            p.address = r['formatted_address']
            p.image_url = photo_url
            p.user_rating = r['rating']
            p.num_ratings = r['user_ratings_total']
            p.place_types = ','.join(r.get('types', []))
            p.place_url = r.get('website')
            lat, lng = r['geometry']['location']['lat'], r['geometry'][
                'location']['lng']
            p.lat = lat
            p.lng = lng
            p.image_attribution = photo_attrib
        if accept_link:
            p.gift_card_url = check_link_against_blacklist(
                suggestion.gift_card_url) or p.gift_card_url
        p.donation_url = p.donation_url or suggestion.donation_url
        p.email_contact = suggestion.email or p.email_contact
        p.save()
        suggestion.processed = True
        suggestion.save()
    if any_added:
        # Note: this is a fairly expensive operation, but should be ok to run
        # once at the end of an admin action
        Area.update_area_for_all_places()
예제 #9
0
    def get_context_data(self, **kwargs):

        from places.models import Place

        context = super(DesktopView, self).get_context_data(**kwargs)

        if self.request.GET.get('srch'):
            from urllib import unquote
            srch = unquote(self.request.GET.get('srch'))
            p = Place.from_name(srch)
            context['srch'] = srch
        else:
            lat = float(self.request.GET.get('lat', 40.7500))
            lon = float(self.request.GET.get('lon', -111.8833))
            p = Place(lat, lon)

        context['place'] = p

        return context
예제 #10
0
def add_theatre(theatre, town=''):
    theatre = re.sub('^(A|An|The) (.*)$', r'\2, \1', theatre.strip())
    theatre_no_the = re.sub(', (A|An|The)$', '', theatre)
    theatre_with_the = '%s, The' % theatre_no_the
    town = town.strip()

    def a_try(**attrs):
        location = Place.objects.get(**attrs)
        log("Found place %s" % location)
        return location

    try:
        return a_try(name=theatre_with_the, town=town)
    except:
        pass

    try:
        return a_try(name=theatre_no_the, town=town)
    except:
        pass

    try:
        return a_try(name='%s, %s' % (theatre_no_the, town), town=town)
    except:
        pass

    try:
        return a_try(name='%s, %s' % (theatre_no_the, town))
    except:
        pass

    if dry_run:
        print "Going to get_or_create place %s, %s" % (theatre, town)
        location = Place(name=theatre, town=town)
    else:
        location, created = Place.objects.get_or_create(name=theatre,
                                                        town=town)
    return location
예제 #11
0
class PlaceGenerator(object):
    """
    Generates Places form file places.txt populated with Google Places
    """
    def __init__(self):
        self.places_file = 'places.txt'

    @transaction.commit_manually
    def run(self):
        try:
            places = open(self.places_file, 'r').readlines()
        except IOError, e:
            print e

        actual_places = []
        for plc in places:
            places.pop()
            places.pop()
            places.pop()
            places.pop()  # LNG:
            places.pop()  # LAT:
            place_name = places.pop()  # NAME:
            places.pop()
            actual_places.append(place_name)

        session_counter = 0
        print colored.white("Generating places:")
        for pls in progress.bar(actual_places):
            place = Place(name=pls)
            session_counter += 1
            place.save()

            if session_counter >= 5000:
                session_counter = 0
                transaction.commit()

        transaction.commit()
예제 #12
0
    def process_search(self, circuit, place_name, lat, lng, location,
                       description):
        """
        invokes search_place and processes the response
        """
        location = location.replace(' ', '-')
        description = description.replace('-', ' ')
        if location == 'The-World' and lat == 'NO-LAT':
            self.print_failed_place(place_name, circuit)
            return

        elif lat == 'NO-LAT' and location is not 'The-World':
            result = self.search_place(
                query=place_name,
                near=location,
            )

        elif lat is not 'NO-LAT' and location == 'The-World':
            result = self.search_place(
                query=place_name,
                ll=lat + ', ' + lng,
            )

        else:
            result = self.search_place(
                query=place_name,
                near=location,
                ll=lat + ', ' + lng,
            )

        if result is None:
            self.print_failed_place(place_name, circuit)
            return

        cat_id = None
        find_venue = False
        if 'venues' in result:
            for field in result['venues']:
                place_name = field['name']
                place_id = field['id']
                find_venue = True
                try:
                    place_phone = field['contact']['phone']
                except KeyError:
                    place_phone = None
                try:
                    place_address = field['location']['address']
                except KeyError:
                    place_address = None
                try:
                    latitude = field['location']['lat']
                    longitud = field['location']['lng']
                    place_coords = Point(latitude, longitud)
                except KeyError:
                    # FIXME: place_coords should not default to 0,0
                    # but for now place_coords is mandatory field on DB
                    place_coords = Point(0, 0)

                for elem in field['categories']:
                    cat_id = elem['id']
                if cat_id is None:
                    cat_id = DEFAULT_PLACE_TYPE_ID

        if find_venue:
            # see if already in DB
            try:
                pl = Place.objects.get(place_id=place_id)
            except Place.DoesNotExist:
                pl = Place()
                pl.name = place_name
                pl.place_id = place_id
                pl.coordinates = place_coords
                if place_phone is not None:
                    pl.phone_number = place_phone
                if place_address is not None:
                    pl.address = place_address
                pl.save()
                try:
                    pt = PlaceType.objects.get(place_type_id=cat_id)
                except PlaceType.DoesNotExist:
                    pt = PlaceType.objects.all()[0]
                pl.place_type.add(pt)
                pl.save()

            cs = CircuitStop()
            cs.circuit = circuit
            cs.place = pl
            cs.description = description
            cs.save()

        else:
            self.print_failed_place(place_name, circuit)
            return
예제 #13
0
    def process_objects(self, circuit):
        results = OrderedDict()
        # multiple = true if creating a place and a CircuitStop
        results['multiple'] = False
        # conflict = CircuitStop with this place already exists
        results['conflict'] = False
        new_place = False

        place = None

        place_id = self.cleaned_data.get('place_id', None)
        print type(place_id)
        if place_id != '':
            try:
                place = Place.objects.get(place_id=place_id)
            except Place.DoesNotExist:
                place = None

        # Enter here if query did not returned a Place
        if place is None:
            # Mandatory fields
            place = Place()
            place.name = self.cleaned_data.get('name', '')
            place.coordinates = Point(
                self.cleaned_data.get('lat'),
                self.cleaned_data.get('lng')
            )
            if place_id is not None:
                place.place_id = place_id
            else:
                # TODO handle case when no place_id is passed
                pass
            # Optional fields
            if 'address' in self.cleaned_data:
                place.address = self.cleaned_data.get('address', '')
            if 'phone_number' in self.cleaned_data:
                place.phone_number = self.cleaned_data.get('phone_number', '')
            if 'website' in self.cleaned_data:
                place.website = self.cleaned_data.get('website', '')
            if 'crossStreet' in self.cleaned_data:
                place.crossStreet = self.cleaned_data.get('crossStreet', '')
            if 'twitter' in self.cleaned_data:
                place.twitter = self.cleaned_data.get('twitter', '')
            # get place_type from db or default
            try:
                place_type = PlaceType.objects.get(
                    place_type_id=self.cleaned_data.get('place_type_id')
                )
            except PlaceType.DoesNotExist:
                place_type = PlaceType.objects.get(
                    place_type_id=DEFAULT_PLACE_TYPE_ID
                )

            place = Place.new_place_save(place, place_type)

            # Sync new Place with MongoDB
            # check_mongo(place)
            # Setting the new place flag to True
            new_place = True

        # Check if the place object has not yet been included in
        # a circuit stop that is part of the circuit
        if circuit.circuit_stops.filter(place=place).exists():
            # There is a conflict with the current state of the
            # resource since there already exists a circuit stop
            # referring to that place
            results['conflict'] = True
            return results

        # Creating a circuit stop for the place
        circuit_stop = CircuitStop(
            circuit=circuit,
            place=place,
            description=self.clean_description(),
            picture=self.cleaned_data.get('picture')
        )

        circuit_stop.save()
        # Now we add it to the circuit
        circuit.circuit_stops.add(circuit_stop)
        circuit.save()
        # Create objects dictionary
        results['circuit_stop'] = circuit_stop
        if new_place:
            results['place'] = place
            results['multiple'] = True
        # Return results dictionary
        return results
예제 #14
0
def addPlace(request, ajax=False, id=None):
    template_name = "add_place_wizard.html" if ajax else "add_place.html"
    sayfa = Sayfa.al_anasayfa()
    lang = request.LANGUAGE_CODE
    user = request.user
    response = {}
    new_place = None
    loged_in = user.is_authenticated()
    photos = []
    profile = user.get_profile()
    ask_phone = not bool(profile.phone.strip()) if profile.phone else True
    if id:
        old_place = get_object_or_404(Place, pk=id)
        photos = list(old_place.photo_set.values_list('id',flat=True))
        if old_place.owner != request.user:
            return HttpResponseForbidden()
        old_place.invalidate_caches()
    else:
        old_place = Place()

    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        login_form = LoginForm(request.POST)
        form = addPlaceForm(request.POST, instance=old_place, req_phone=ask_phone)
        if form.is_valid():
            new_place=form.save(commit=False)
            new_place.translation_check()
#            if register_form.is_valid() or loged_in:
#                if not loged_in:
#                    user = register_form.save(commit=False)
#                    user.username = user.email
#                    user.set_password(register_form.cleaned_data['pass1'])
#                    user.save()
            phone = form.cleaned_data.get('phone')
            if phone:
                profile.phone = phone
                profile.save()
            new_place.owner = user
            new_place.lat = str(new_place.lat)
            new_place.lon = str(new_place.lon)
            new_place.lang = request.LANGUAGE_CODE
#            log.info('%s %s '% (new_place.lang, request.LANGUAGE_CODE))
            new_place.save()
            form.save_m2m()
            for tag in form.cleaned_data['tags']:
                new_place.tags.add(tag)
#            log.info(form.cleaned_data['tags'])

            new_place.save()
            d, new = Description.objects.get_or_create(place=new_place, lang=new_place.lang)
            d.text = new_place.description
            d.title = new_place.title
            d.save()
            tmp_photos = request.session.get('tmp_photos')
            if tmp_photos:
                Photo.objects.filter(id__in=tmp_photos).update(place=new_place)
                if tmp_photos[0]:
                    p=Photo.objects.filter(pk=tmp_photos[0])
                    if p: p[0].save()
                request.session['tmp_photos']=[]
            if not ajax:
                if not new_place.published:
                    messages.success(request, _('Your place succesfully saved but not published yet.'))
                    messages.info(request, _('You can publish this place by pressing the "Publish" button below.'))
                else:
                    messages.success(request, _('Your changes succesfully saved.'))
                return HttpResponseRedirect('%s#do_listPlaces,this'%reverse('dashboard'))
        else:
            for e in form.errors:
                messages.error(request, e)
        if ajax:
            response = {
                'user':getattr(user,'username'),
                'loged_in':loged_in,
#                'new_place':repr(new_place),
                'errors':form.errors,
                'new_place_id':getattr(new_place,'id',0),
            }
            return HttpResponse(json.dumps(response), mimetype='application/json')


    else:
        form = addPlaceForm(instance=old_place, req_phone=ask_phone)
        register_form = RegisterForm()
        login_form = LoginForm()
    str_fee =  _('%s Service Fee '% configuration('host_fee'))
    context = {'form':form, 'rform':register_form,'lform':login_form,'place':old_place,
               'host_fee':configuration('host_fee'), 'str_fee':str_fee, 'photos':photos,
               'tags':TagTranslation.objects.filter(lang=request.LANGUAGE_CODE),
               'existing_tags':[],

    }
    if id:
        context['existing_tags'] = old_place.tags.values_list('id',flat=True)
    return render_to_response(template_name, context, context_instance=RequestContext(request))
예제 #15
0
import django
import sys
import os
sys.path.append(os.path.dirname(__file__) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'carebackend.settings'
django.setup()
from places.models import Place
import pandas as pd
import sys

fl = sys.argv[1]

df = pd.read_csv(fl)

for _, row in df.iterrows():
    try:
        p = Place.objects.get(place_id=row['place_id'])
    except Place.DoesNotExist:
        p = Place(place_id=row['place_id'])

    p.lat = row['lat']
    p.lng = row['lng']
    p.address = row['formatted_address']
    p.user_rating = row['rating']
    if not p.name:
        p.name = row['name']
    p.num_ratings = row['user_ratings_total']
    p.gift_card_url = row.get('gift_card_url')
    p.photo_attribution = row['image_attribution']
    p.image_url = row['photo_url']
    p.save()
예제 #16
0
 def save(self):
     new_place = Place(**self.cleaned_data)
     new_place.save()
     return new_place
예제 #17
0
django.setup()
from places.models import Place
import pandas as pd
import sys
from places.google_places_helper import fetch_details_for_place_id

fl = sys.argv[1]

df = pd.read_csv(fl)

for _, row in df.iterrows():
    place_id = row['place_id']
    try:
        p = Place.objects.get(place_id=place_id)
    except Place.DoesNotExist:
        p = Place(place_id=place_id)

        r, photo_url, photo_attrib = fetch_details_for_place_id(place_id)
        if not r.get('rating'):  # probably not meaningful place
            continue
        p.name = r['name']
        p.address = r['formatted_address']
        p.image_url = photo_url
        p.user_rating = r['rating']
        p.num_ratings = r['user_ratings_total']
        p.place_types = ','.join(r.get('types', []))
        p.place_url = r.get('website')
        lat, lng = r['geometry']['location']['lat'], r['geometry']['location']['lng']
        p.lat = lat or row['lat']
        p.lng = lng or row['lng']
        p.image_attribution = photo_attrib