当前位置: 首页>>代码示例>>Python>>正文


Python Place.save方法代码示例

本文整理汇总了Python中models.Place.save方法的典型用法代码示例。如果您正苦于以下问题:Python Place.save方法的具体用法?Python Place.save怎么用?Python Place.save使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在models.Place的用法示例。


在下文中一共展示了Place.save方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: query

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
def query(request):
	if request.method == 'POST':
		latitude_pass = request.POST.get('lat', None)
		longitude_pass = request.POST.get('long', None)	
	else:
		latitude_pass = request.GET.get('lat', None)
		longitude_pass = request.GET.get('long', None)	
		
	if latitude_pass and longitude_pass:
		now = datetime.utcnow().replace(tzinfo=tz.tzutc())
		# guess[0] = place name, guess[1] = place lat, guess[2] = place longitude
		guess = searchPlaces(latitude_pass, longitude_pass)
		places = [obj.name for obj in Place.objects.all()]
		# use it from db if already exist, otherwise create a new one
		if guess[0] not in places:
			predict = Place(name=guess[0], latitude=guess[1], longitude=guess[2], time=now)
			predict.save()
		else:
			predict = Place.objects.get(name=guess[0])
		Track(
			latitude = latitude_pass,
			longitude = longitude_pass,
			prediction=predict,
			time=now
			).save()
		return HttpResponse('GET successful')
	else:
		return redirect('/')
开发者ID:yyl,项目名称:track-map,代码行数:30,代码来源:views.py

示例2: test_good_google_location_and_yelp

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
 def test_good_google_location_and_yelp(self):
   place = Place()
   place.name = "Whole Foods"
   place.location = '1240 Yale St, Santa Monica, CA 90404'
   place.save()
   self.assertEqual(place.yelp_id, 'hdQJrF3Fw_KrEaDywC3tyg')
   self.assertEqual(len(Place.objects.all()), 1)
开发者ID:jflinter,项目名称:paleomaps,代码行数:9,代码来源:tests.py

示例3: createentrycontinue

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
def createentrycontinue(request):
	title = request.POST['title'].replace(" ", "_")
	location = request.POST['location']
	comments = request.POST['details']
	p = Place(name = title, location=location, details=comments)
	p.save()
	return render_to_response('places/createpagecontinue.html', {"placename": p.name}, context_instance=RequestContext(request))
开发者ID:TandZ,项目名称:Crowd,代码行数:9,代码来源:views.py

示例4: createNew

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
def createNew(request):
    if request.method == 'POST':
        payload = json.loads(request.body)
        thisx, thisy = payload.get('location', None).split(',')
        pnt = GEOSGeometry('POINT(%s %s)' % (thisx, thisy))
        this_place = Place(name = payload.get('name', None), location = pnt)
        this_place.save()
        return HttpResponse('Success')
    else:
        return HttpResponseBadRequest('Missing POST data')
开发者ID:artagnon,项目名称:irale,代码行数:12,代码来源:views.py

示例5: savePlace

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
def savePlace(request):
    tokenId = request.GET["token"]
    voiceId = request.GET["voiceId"]
    placeId = request.GET["placeId"]
    lat = request.GET["lat"]
    lon = request.GET["lon"]

    user = User.objects.get(tokenHash=tokenId)
    voice = Voice.objects.get(sender=user, id=voiceId)
    place = Place(voice=voice, placeId=placeId, latitude=lat, longitude=lon);
    place.save()



    return JsonResponse({"success" : "1" })
开发者ID:tanlah,项目名称:echoesapp-backend,代码行数:17,代码来源:views.py

示例6: test_simple_place_creation

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
    def test_simple_place_creation(self):
        """
        Creates test place
        """
        places = Place.objects.filter(name = "Test Place")
        [place.delete() for place in places]

        place = Place()
        place.name = "Test Place"
        place.capacity = 20
        place.save()

        place = Place.objects.filter(name = "Test Place")
        print place
        self.assertNotEqual(place, None)
开发者ID:RadoRado,项目名称:checkin-at-fmi,代码行数:17,代码来源:tests.py

示例7: add

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
def add(request):
  
  if request.method == 'POST':
    form = PlaceForm(request.POST)
    if form.is_valid():
      p = Place(name=form.cleaned_data['name'], address=form.cleaned_data['address'], city=form.cleaned_data['city'], creator=request.user)
      p.save()
      
      # Redirect to place view
      return HttpResponseRedirect(p.get_absolute_url())
  else:
    form = PlaceForm()
  
  return {
  
    'form' : form,
  }
开发者ID:La0,项目名称:beers,代码行数:19,代码来源:views.py

示例8: createEvent

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
	def createEvent(sessionId,eventArgs):
		'''
		Метод для создания событий (по сессии и списку аргументов)
		'''
		userId = SessionManager.getUser(sessionId)
		eName = 'Noname event'
		eTime = '2012-12-31'
		eDescription = 'No defenition'
		photo = Photo.objects.get(pk = 1)
		eEventTypeId = 1
		eLatitude = 0
		eLongitude = 0
		eCountryId = Country.objects.get(pk = 1)
		eCityId = City.objects.get(pk = 1)
		eNamePlace = 'Noname place'
		
		if eventArgs.has_key('name'):
			eName = eventArgs['name']
			
		if eventArgs.has_key('time'):
			eTime = eventArgs['time']
			
		if eventArgs.has_key('description'):
			eDescription = eventArgs['description']
			
		if eventArgs.has_key('photo'):
			photo = Photo(photo = eventArgs['photo'])
			photo.save()
		else:
			photo = Photo.objects.get(pk = 1)
			
		if eventArgs.has_key('eventTypeId'):
			eEventTypeId = eventArgs['eventTypeId']
			
		if eventArgs.has_key('longitude'):
			eLatitude = eventArgs['longitude']
			
		if eventArgs.has_key('latitude'):
			eLongitude = eventArgs['latitude']	
		
		
		place = Place(cityId = eCityId, countryId = eCountryId, name = eNamePlace, latitude = eLatitude, longitude = eLongitude)
		place.save()
		newEvent = Event(creatorId = userId, name = eName, time = eTime, description = eDescription, photoId = photo, eventTypeId_id = eEventTypeId, PlaceId = place)
		newEvent.save()
		return newEvent.pk
开发者ID:bekas,项目名称:MeToo,代码行数:48,代码来源:eventManager.py

示例9: create_place

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
 def create_place(self,request):
     u = self.current_user(request)
     country = city = code = ''
     for k,v in request.POST.items():
         if 'country' in k: country = v
         elif 'city' in k: city = v
         elif 'code' in k: code = v.replace('-','').replace(' ','')
     place = Place.objects.filter(user=u)
     if len(place): 
         p = place[0]
         p.country = country
         p.city = city
         p.code = code
         p.save()
     else:
         p = Place(user=u,country=country,city=city,code=code)
         p.save() 
     return response('Place created/updated sucessfully')
开发者ID:efforia,项目名称:eos-dashboard,代码行数:20,代码来源:control.py

示例10: loadxlsdata

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
def loadxlsdata(args):
    import settings
    import re
    
    from places.models import Place
    
    filepath = settings.XLSDIR + '\\xls.dat' 
    lines = [line.strip() for line in open(filepath)]
    
    howmany = 0 if args.howmany <= 0 else args.howmany 
    
    reobj = re.compile(r"\d+-\d+-(?P<districtno>\d+)")    
    linecount = 0
    for line in lines:
        if line and line[0].isalpha():
            # get district number from this string
	    match = reobj.search(line)
	    if not match:
		raise Exception("Failed to find expected district number")
	    districtno = int(match.group("districtno"))
            continue
	elif line and line[0] == '{':
	    pass
	else:
	    continue
        
        rec = eval(line)
        p = Place()
        p.provinceno = rec['provinceno']
        p.districtno = districtno
        p.cantonno = rec['districtno']
        p.territoryno = rec['territoryno']
        p.blockno = rec['blockno'] if 'blockno' in rec else None
        p.houseno = rec['houseno']
        p.districtname = rec['districtname']
        p.directions = rec['directions']
        p.notes = rec['notes']
        p.save()
        
        linecount += 1
        if linecount and linecount == howmany:
            break
开发者ID:holandacz,项目名称:ourfield,代码行数:44,代码来源:commands.py

示例11: placesOnPath

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
def placesOnPath(path):
	count = 0
	for point in path:
		pointplaces = googlePlaces(point.latitude, point.longitude)
		for place in pointplaces:
			place.get_details()
			if not existing(Place.objects.all(), place) and hasRoute(place):
				now = datetime.utcnow().replace(tzinfo=tz.tzutc())
				predict = Place(name=place.name, 
								latitude=place.geo_location['lat'], 
								longitude=place.geo_location['lng'], 
								address=place.formatted_address,
								point=point,
								time=now)
				if count == 0:
					predict.right = isRightSide(point, path[count+1], predict)
				else:
					predict.right = isRightSide(path[count-1], point, predict)
				predict.save()	
		count += 1
开发者ID:yyl,项目名称:track-map,代码行数:22,代码来源:views.py

示例12: save_geojson

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
def save_geojson(request):
    data = json.loads(request.POST.get('data', None))
    if not data:
        return HttpResponse(json.dumps({'error': 'no data'}))
    osm_id = data['properties']['osm_id']
    geom_string = json.dumps(data['geometry'])
    feature_md5 = md5(geom_string + str(osm_id)).hexdigest()
    try:
        existing_place = Place.objects.get(md5=feature_md5)
        existing_place.is_flooded = data['properties']['is_flooded']
        existing_place.save()
        return HttpResponse(json.dumps(existing_place.get_geojson()))
    except:
        pass
    new_place = Place()
    new_place.osm_id = osm_id
    new_place.is_flooded = data['properties']['is_flooded']
    new_place.geom = json.dumps(data['geometry'])
    new_place.md5 = feature_md5
    new_place.properties = json.dumps(data['properties'])
    new_place.save()
    return HttpResponse(json.dumps(new_place.get_geojson()))
开发者ID:batpad,项目名称:doha-example,代码行数:24,代码来源:views.py

示例13: OneToOneTests

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
class OneToOneTests(TestCase):

    def setUp(self):
        self.p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
        self.p1.save()
        self.p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
        self.p2.save()
        self.r = Restaurant(place=self.p1, serves_hot_dogs=True, serves_pizza=False)
        self.r.save()

    def test_getter(self):
        # A Restaurant can access its place.
        self.assertEqual(repr(self.r.place), '<Place: Demon Dogs the place>')
        # A Place can access its restaurant, if available.
        self.assertEqual(repr(self.p1.restaurant), '<Restaurant: Demon Dogs the restaurant>')
        # p2 doesn't have an associated restaurant.
        self.assertRaises(Restaurant.DoesNotExist, getattr, self.p2, 'restaurant')

    def test_setter(self):
        # Set the place using assignment notation. Because place is the primary
        # key on Restaurant, the save will create a new restaurant
        self.r.place = self.p2
        self.r.save()
        self.assertEqual(repr(self.p2.restaurant), '<Restaurant: Ace Hardware the restaurant>')
        self.assertEqual(repr(self.r.place), '<Place: Ace Hardware the place>')
        self.assertEqual(self.p2.pk, self.r.pk)
        # Set the place back again, using assignment in the reverse direction.
        self.p1.restaurant = self.r
        self.assertEqual(repr(self.p1.restaurant), '<Restaurant: Demon Dogs the restaurant>')
        r = Restaurant.objects.get(pk=self.p1.id)
        self.assertEqual(repr(r.place), '<Place: Demon Dogs the place>')

    def test_manager_all(self):
        # Restaurant.objects.all() just returns the Restaurants, not the Places.
        self.assertQuerysetEqual(Restaurant.objects.all(), [
            '<Restaurant: Demon Dogs the restaurant>',
        ])
        # Place.objects.all() returns all Places, regardless of whether they
        # have Restaurants.
        self.assertQuerysetEqual(Place.objects.order_by('name'), [
            '<Place: Ace Hardware the place>',
            '<Place: Demon Dogs the place>',
        ])

    def test_manager_get(self):
        def assert_get_restaurant(**params):
            self.assertEqual(repr(Restaurant.objects.get(**params)),
                             '<Restaurant: Demon Dogs the restaurant>')
        assert_get_restaurant(place__id__exact=self.p1.pk)
        assert_get_restaurant(place__id=self.p1.pk)
        assert_get_restaurant(place__exact=self.p1.pk)
        assert_get_restaurant(place__exact=self.p1)
        assert_get_restaurant(place=self.p1.pk)
        assert_get_restaurant(place=self.p1)
        assert_get_restaurant(pk=self.p1.pk)
        assert_get_restaurant(place__pk__exact=self.p1.pk)
        assert_get_restaurant(place__pk=self.p1.pk)
        assert_get_restaurant(place__name__startswith="Demon")

        def assert_get_place(**params):
            self.assertEqual(repr(Place.objects.get(**params)),
                             '<Place: Demon Dogs the place>')
        assert_get_place(restaurant__place__exact=self.p1.pk)
        assert_get_place(restaurant__place__exact=self.p1)
        assert_get_place(restaurant__place__pk=self.p1.pk)
        assert_get_place(restaurant__exact=self.p1.pk)
        assert_get_place(restaurant__exact=self.r)
        assert_get_place(restaurant__pk=self.p1.pk)
        assert_get_place(restaurant=self.p1.pk)
        assert_get_place(restaurant=self.r)
        assert_get_place(id__exact=self.p1.pk)
        assert_get_place(pk=self.p1.pk)

    def test_foreign_key(self):
        # Add a Waiter to the Restaurant.
        w = self.r.waiter_set.create(name='Joe')
        w.save()
        self.assertEqual(repr(w), '<Waiter: Joe the waiter at Demon Dogs the restaurant>')
        # Query the waiters
        def assert_filter_waiters(**params):
            self.assertQuerysetEqual(Waiter.objects.filter(**params), [
                '<Waiter: Joe the waiter at Demon Dogs the restaurant>'
            ])
        assert_filter_waiters(restaurant__place__exact=self.p1.pk)
        assert_filter_waiters(restaurant__place__exact=self.p1)
        assert_filter_waiters(restaurant__place__pk=self.p1.pk)
        assert_filter_waiters(restaurant__exact=self.p1.pk)
        assert_filter_waiters(restaurant__exact=self.p1)
        assert_filter_waiters(restaurant__pk=self.p1.pk)
        assert_filter_waiters(restaurant=self.p1.pk)
        assert_filter_waiters(restaurant=self.r)
        assert_filter_waiters(id__exact=self.p1.pk)
        assert_filter_waiters(pk=self.p1.pk)
        # Delete the restaurant; the waiter should also be removed
        r = Restaurant.objects.get(pk=self.p1.pk)
        r.delete()
        self.assertEqual(Waiter.objects.count(), 0)

    def test_multiple_o2o(self):
        # One-to-one fields still work if you create your own primary key
#.........这里部分代码省略.........
开发者ID:ssaltzman,项目名称:POET,代码行数:103,代码来源:tests.py

示例14: test_bad_google_location

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
 def test_bad_google_location(self):
   place = Place()
   place.name = "test place"
   place.location = ''
   place.save()
   self.assertEqual(len(Place.objects.all()), 0)
开发者ID:jflinter,项目名称:paleomaps,代码行数:8,代码来源:tests.py

示例15: acquisition

# 需要导入模块: from models import Place [as 别名]
# 或者: from models.Place import save [as 别名]
def acquisition(request):
    record_data = {}
    record = None

    if request.GET.get('isbn'):
        isbn = request.GET.get('isbn')
        if isbnpy.isValid(isbn):
            url = 'http://openlibrary.org/api/volumes/brief/json/isbn:' + isbn
            response = urllib2.urlopen(url)
            # response = urllib2.urlopen('http://127.0.0.1/json/3.json')
            data = json.load(response)
            if isbnpy.isI10(isbn):
                isbn = isbnpy.convert(isbn)
            if data == {}:
                record_data['isbn13'] = isbn
                record_form = RecordForm(instance=record)
                return render(request, 'acquisition.html', {'data': record_data, 'form': record_form})
            data = data.itervalues().next()['records'].itervalues().next()

            try:
                record = Record.objects.get(isbn13=isbn)
                new_record = False
            except Record.DoesNotExist:
                record = Record(isbn13=isbn)
                new_record = True
                # pp(data)
            if record.book_id:
                book = record.book
            else:
                book = Book()

            book.title = data['data']['title']
            if data['details']['details'].has_key('subtitle'):
                book.subtitle = data['details']['details']['subtitle']
            book.save()

            if data['details']['details'].has_key('pagination'):
                record.pagination = data['data']['pagination']
            elif data['details']['details'].has_key('number_of_pages'):
                record.pagination = str(data['data']['number_of_pages']) + ' p.'

            if data['details']['details'].has_key('physical_format'):
                record.format = data['details']['details']['physical_format']
                if record.format.startswith('electronic'):
                    record.format = 'eBook'
                    # record.openlibrary_url = data['data']['url']

            if data['details']['details'].has_key('weight'):
                record.weight = data['details']['details'].get('weight')
            if data['details']['details'].has_key('physical_dimensions'):
                record.dimensions = data['details']['details'].get('physical_dimensions')

            if data['data'].has_key('classifications'):
                if data['data']['classifications'].has_key('dewey_decimal_class'):
                    record.ddc = data['data']['classifications'].get('dewey_decimal_class')[0]
                if data['data']['classifications'].has_key('lc_classifications'):
                    record.lcc = data['data']['classifications'].get('lc_classifications')[0]

            try:
                record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%B %d, %Y').date()
                record.publication_has_month = True
                record.publication_has_day = True
            except ValueError:
                try:
                    record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%Y').date()
                    record.publication_has_month = False
                    record.publication_has_day = False
                except ValueError:
                    try:
                        record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%B %Y').date()
                        record.publication_has_day = False
                        record.publication_has_month = True
                    except ValueError:
                        record.date_of_publication = datetime.strptime(data['data']['publish_date'], '%m/%d/%Y').date()
                        record.publication_has_day = True
                        record.publication_has_month = True

            if data['data'].has_key('identifiers'):
                if data['data']['identifiers'].has_key('openlibrary'):
                    record.openlibrary_id = data['data']['identifiers']['openlibrary'][0]
                if data['data']['identifiers'].has_key('goodreads'):
                    record.goodreads_id = data['data']['identifiers']['goodreads'][0]
                if data['data']['identifiers'].has_key('librarything'):
                    record.librarything_id = data['data']['identifiers']['librarything'][0]
                if data['data']['identifiers'].has_key('oclc'):
                    record.oclc_id = data['data']['identifiers']['oclc'][0]
                if data['data']['identifiers'].has_key('lccn'):
                    record.lccn_id = data['data']['identifiers']['lccn'][0]

            if data['data'].has_key('by_statement'):
                record.by_statement = data['data'].get('by_statement')

            if data['data'].has_key('notes'):
                record.notes = data['data'].get('notes')

            if data['data'].has_key('excerpts'):
                record.excerpt = data['data'].get('excerpts')[0].get('text')

            record.book = book

#.........这里部分代码省略.........
开发者ID:ratna1234,项目名称:nerp,代码行数:103,代码来源:views.py


注:本文中的models.Place.save方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。