def address_create(): address_form = AddressForm(request.form) user = auth.get_logged_in_user() if request.method == "POST": address = Address( user = user, street=address_form.street.data, zipcode=address_form.zipcode.data, state=address_form.state.data, country=address_form.country.data ) address.save() flash("Address successfully saved") return redirect(url_for("dashboard")) elif request.method == "GET": try: exist = Address.select().where(Address.user == user).get() return redirect(url_for("address")) except Address.DoesNotExist: if request.method == "POST": address = Address( user = user, street=address_form.street.data, zipcode=address_form.zipcode.data, state=address_form.state.data, country=address_form.country.data ) address.save() flash("Address successfully saved") return redirect(url_for("dashboard")) else: return render_template("address_create.html", address_form=address_form)
def save_order_addresses(id): user_authenticated_id = get_jwt_identity() pickup_address = Address(address=request.json.get('pickup').get('address'), city=request.json.get('pickup').get('city'), country=request.json.get('pickup').get('country'), cp=request.json.get('pickup').get('CP'), user_id=user_authenticated_id) pickup_address.save() delivery_address = Address( address=request.json.get('delivery').get('address'), city=request.json.get('delivery').get('city'), country=request.json.get('delivery').get('country'), cp=request.json.get('delivery').get('CP'), user_id=user_authenticated_id) delivery_address.save() order = Order.query.get(id) order.address_delivery = delivery_address order.address_pickup = pickup_address order.save() DBManager.commitSession() order_new_data_mail(order) return jsonify(order.serializeForEditView()), 200
def addsite(request): uid = request.session.get('id') udata = Userinfo.objects.get(id=uid) if request.method == 'POST': address = Address() address.receiver = request.POST.get('receiver').strip() address.detaiarea = request.POST.get('detaiarea').strip() address.postcode = request.POST.get('postcode').strip() address.phone = request.POST.get('phone').strip() address.auser = udata address.save() if address.pk: return HttpResponseRedirect('/user/site/') content = {'udata': udata} return render(request, 'home/f_users/user_center_addsite .html', content)
def test_should_have_user_as_addressable(self): """ Prueba que una direccion pueda ser asociada a un usuario """ user = User(email="*****@*****.**", name="nada", last_name="mas") user.save() address = Address() address.street1 = "Cra 7 # 6-19" address.addressable_object = user address.save() address_from_db = Address.objects.get(id=address.id) self.assertEqual(address_from_db.addressable_type.name, 'user')
def test_should_have_creditcard_as_addressable(self): """ Prueba que una direccion pueda ser asociada a una tarjeta de credito """ credit_card = CreditCard(number="1111111111") credit_card.save() address = Address() address.street1 = "Cra 7 # 6-19" address.addressable_object = credit_card address.save() address_from_db = Address.objects.get(id=address.id) self.assertEqual(address_from_db.addressable_type.name, 'credit card')
def test_should_have_store_as_addressable(self): """ Prueba que una direccion pueda ser asociada a una tienda """ store = Store(name="My store") store.save() address = Address() address.street1 = "Cra 7 # 6-19" address.addressable_object = store address.save() address_from_db = Address.objects.get(id=address.id) self.assertEqual(address_from_db.addressable_type.name, 'store')
def test_should_have_store_location_as_addressable(self): """ Prueba que una direccion pueda ser asociada a una ubicacion de tienda """ store = StoreLocation(city="Chia") store.save() address = Address() address.street1 = "Cra 7 # 6-19" address.addressable_object = store address.save() address_from_db = Address.objects.get(id=address.id) self.assertEqual(address_from_db.addressable_type.name, 'store location')
def registration(request): if request.user.is_authenticated(): # ideal, but not created yet, going with homepage #return HttpResponseRedirect('/profile/') return HttpResponseRedirect('/') if request.method == 'POST': #fills out with whatever was posted form = RegistrationForm(request.POST) # runs all clean methods in form if form.is_valid(): try: #customer exists cusAlreadyExists = User.objects.get(username= form.cleaned_data['username']) username_taken = True context = {'form': form, 'username_taken': username_taken} return render_to_response('register.html', context, context_instance=RequestContext(request)) except User.DoesNotExist: #customer did not exist user = User.objects.create_user( username=form.cleaned_data['username'], password=form.cleaned_data['password1']) user.save() addr = Address( AddressLineOne = form.cleaned_data['street'], City = form.cleaned_data['city'], State = form.cleaned_data['state'], ZIPCode = form.cleaned_data['zipcode'] ) addr.save() customer = Customer(user=user, Address=addr, FirstName = form.cleaned_data['firstName'], LastName = form.cleaned_data['lastName'] ) customer.save() customer = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) login(request, customer) return HttpResponseRedirect('/') else: return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request)) else: #user not submitting the form, send blank form form = RegistrationForm() context = {'form': form} return render_to_response('register.html', context, context_instance=RequestContext(request))
def get_or_create_person(address_tuple): name, email_address = address_tuple existing_addresses = Address.objects.filter(email=email_address.lower()) if len(existing_addresses) == 0: new_person = Person(name=name) new_person.save() new_address = Address(email=email_address.lower(), person=new_person) new_address.save() return new_address elif len(existing_addresses) > 0: if len(existing_addresses) > 1: print "found multiple db entries for address %s - returning first" % email_address existing_address = existing_addresses[0] if existing_address.person.name == '': existing_address.person.name = name existing_address.person.save() return existing_address
def get_address_by_coordinates(latitude, longitude): """Returns address object by coordinates""" try: address = Address.objects.get(latitude=Decimal(latitude), longitude=Decimal(longitude)) except ObjectDoesNotExist: try: address_chunks = gm_get_location(Decimal(latitude), Decimal(longitude)) except: return None town, created = Town.objects.get_or_create(name=address_chunks['town']) street, created = Street.objects.get_or_create(name=address_chunks['street'], town=town) street_number = address_chunks['number'] address = Address(street=street, street_number=street_number) address.save() else: return None return address
def import_places(temp_file, extra_params, name, description=None, private=False, user=None, existing='update', encoding='utf-8', error_cb=None, progress_cb=None, context=None, format='CSV'): log.debug('Processing file %s with this extra params %s', temp_file, extra_params) errors=[] def add_error(line, msg): errors.append(_('Line %d - %s') % (line, msg)) if error_cb: error_cb(line, msg) file_reader=fmt.get_fmt_descriptor(format).reader(temp_file, extra_params) exists=PlacesGroup.objects.filter(name=name, private=False).exclude(created_by=user).count() if exists: add_error(0, _('Collection with same name was created by other user')) return group, created= PlacesGroup.objects.get_or_create_ns(name=name, created_by=user) if created: group.description=description group.private=private group.save(user=user) elif existing=='remove': group.places.all().delete() num_lines = file_reader.count() with file_reader: line=0 while True: line+=1 log.debug('Processing line %d', line) try: l=file_reader.next() except StopIteration: break except LineError, e: add_error(line, e.message) continue except Exception, e: add_error(line, _('File reading error (%s)')% str(e)) traceback.print_exc() break place_name=l['name'] try: place=Place.objects.get(name=place_name, group=group) except Place.DoesNotExist: place=None if place and existing=='skip': log.debug('Skipping line %d as existing', line) if existing=='update' or not place: try: with transaction.atomic(): if not place: place=Place(name=place_name, group=group) address=None if l.get('address'): address=Address(**l['address']) place.description=l.get('description') place.url=l.get('url') if l.get('position'): pos=l['position'] place.position=Point(*pos, srid=4326) else: #geocode from address try: new_address,point=geocode.get_coordinates_remote(address, context=context) except geocode.NotFound: raise LineError( _('Cannot get location for address %s')% unicode(address)) except remote.TimeoutError: raise LineError(_('Geocoding process is not responding')) except remote.RemoteError, e: raise LineError( _('Geocoding process error (%s)')% str(e)) # except geocode.ServiceError, e: # raise LineError( _('Geocoding Error (%s)')% str(e)) # except ValueError,e: # raise LineError(_('Data Error (%s)')% str(e)) place.position=point try: if address: address.save(user=user) place.address=address place.save(user=user) except MaxObjectsLimitReached: add_error(line, _('Reached limit of records per user')) break except Exception, e: raise LineError( _('Error saving line (%s)')%str(e))
class SeasonTest(TestCase): def setUp(self): # create classifcation self.classification = create_classification('Men\'s Open') # create an Address and a Field self.address = Address(street='ABC Street') self.address.save() self.field = Field(name='Field 1', address=self.address) self.field.save() # create teams self.team_1 = create_team('Team 1', self.classification) self.team_2 = create_team('Team 2', self.classification) # create some players self.player_1 = create_player('One', '1') self.player_2 = create_player('Two', '2') self.player_3 = create_player('Three', '3') # assign the players self.playfor_1 = PlayFor(player=self.player_1, team=self.team_1, from_date=datetime.date.today()) self.playfor_1.save() self.playfor_2 = PlayFor(player=self.player_2, team=self.team_1, from_date=datetime.date.today()) self.playfor_2.save() self.playfor_3 = PlayFor(player=self.player_3, team=self.team_1, from_date=datetime.date.today()) self.playfor_3.save() # create referee person = Person(first_name='Ref', last_name='Ref') person.save() self.referee = Referee(person=person) self.referee.save() # create two seasons self.season_1 = create_season(self.classification, 'Division 1', '2014-2015', datetime.date.today(), datetime.date.today()) self.season_2 = create_season(self.classification, 'Division 2', '2015-2016', datetime.date.today(), datetime.date.today()) # create some games self.matchday_season_1 = Matchday(season=self.season_1, label='1', date=datetime.date.today()) self.matchday_season_1.save() self.game_season_1 = Game(matchday=self.matchday_season_1, date=datetime.date.today(), away_team=self.team_1, home_team=self.team_2, referee=self.referee, played=True, field=self.field) self.game_season_1.save() self.matchday_season_2 = Matchday(season=self.season_2, label='2', date=datetime.date.today()) self.matchday_season_2.save() self.game_season_2 = Game(matchday=self.matchday_season_2, date=datetime.date.today(), away_team=self.team_1, home_team=self.team_1, referee=self.referee, played=True, field=self.field) self.game_season_2.save() def test_player_season(self): # add team to season self.season_1.enrolled.add(self.team_1) self.assertItemsEqual((self.team_1,), self.player_1.teams_per(self.season_1)) def test_goals_by_season(self): # 2 goals in season 1 by player 1 goal_1 = Goal(scored_by=self.playfor_1, scored_for=self.team_1, game=self.game_season_1) goal_1.save() goal_2 = Goal(scored_by=self.playfor_1, scored_for=self.team_1, game=self.game_season_1) goal_2.save() # 1 goal by player 1 in season 2 goal_x = Goal(scored_by=self.playfor_1, scored_for=self.team_1, game=self.game_season_2) goal_x.save() # 1 goal in season 2 by player 2 goal_3 = Goal(scored_by=self.playfor_2, scored_for=self.team_1, game=self.game_season_2) goal_3.save() # 1 own goal in season 1 by player 3 goal_4 = Goal(scored_by=self.playfor_3, scored_for=self.team_2, game=self.game_season_1) goal_4.save() self.assertIn(self.player_1, self.season_1.scorers()) self.assertNotIn(self.player_2, self.season_1.scorers()) self.assertNotIn(self.player_3, self.season_1.scorers()) self.assertEqual(3, self.season_1.count_goals()) self.assertEqual(2, self.season_1.scorers()[0].num_scored) def test_disciplinary(self): yellow_card_1 = Card(color='Y', play_for=self.playfor_1, in_game=self.game_season_1) yellow_card_1.save() yellow_card_2 = Card(color='Y', play_for=self.playfor_1, in_game=self.game_season_1) yellow_card_2.save() yellow_card_3 = Card(color='Y', play_for=self.playfor_1, in_game=self.game_season_2) yellow_card_3.save() red_card_1 = Card(color='R', play_for=self.playfor_3, in_game=self.game_season_1) red_card_1.save() self.assertItemsEqual((self.playfor_1, self.playfor_3), self.season_1.booked_playfors()) self.assertEqual(2, self.season_1.booked_playfors()[0].num_of_cards) self.assertEqual(2, self.season_1.yellow_booked_playfors()[0].num_of_cards) self.assertItemsEqual((self.playfor_3,), self.season_1.red_booked_playfors()) self.assertEqual(1, self.season_1.red_booked_playfors()[0].num_of_cards) num_of_yellows = self.\ playfor_1.count_yellow_cards_per(self.season_1) self.assertEqual(num_of_yellows, 2) def test_get_season(self): # create two seasons classification = Classification(label='test mens') classification.save() competition = Competition( name='div 1', mode='l', classification=classification ) competition.save() season_1 = Season(label='s1', start_date=datetime.date.today(), end_date=datetime.date.today() + datetime.timedelta(365), competition=competition, published=True ) season_2 = Season(label='s2', start_date=datetime.date.today() + datetime.timedelta(365), end_date=datetime.date.today() + datetime.timedelta(730), competition=competition ) season_1.save() season_2.save() self.assertIn(season_1, Season.get_current_season_by_slugs('test-mens', 'div-1')) self.assertNotIn(season_2, Season.get_current_season_by_slugs('test-mens', 'div-1'))
def do(request, nid, aid, browser_tab): WZ = Z.SetWhoZwho(request, browser_tab) if WZ['ErrorMessage']: return GoLogout(request, WZ) try: name = Name.objects.get(pk=int(nid)) except: return GoLogout(request, WZ, "[EA01]: URL containd an invalid name ID.") if WZ['Authority'] < Z.Admin and name.owner != WZ['AuthorizedOwner']: return GoLogout(request, WZ, "[EA02]: URL containd an invalid name ID.") if aid != '0': try: address = Address.objects.get(pk=int(aid)) except: return GoLogout(request, WZ, "[EA03]: URL containd an invalid addressID.") if address.owner != name.owner: return GoLogout(request, WZ, "[EA04]: URL containd an invalid address ID.") if WZ['Authority'] < Z.Admin and address.owner != WZ['AuthorizedOwner']: return GoLogout(request, WZ, "[EA05]: URL containd an invalid ID.") if request.method == 'POST': # If the form has been submitted... form = DirectoryEditAddressForm(request.POST, request.FILES) if form.is_valid(): if aid == '0': address = Address() address.owner = name.owner address.street = form.cleaned_data['street'] address.address_line2 = form.cleaned_data['address_line2'] address.municipality = form.cleaned_data['municipality'] address.city = form.cleaned_data['city'] address.province = form.cleaned_data['province'] address.country = form.cleaned_data['country'] address.postcode = form.cleaned_data['postcode'] address.phone = form.cleaned_data['home_phone'] address.save() if aid == '0': name.address_id = address.id name.save() logger.info(WZ['User'] + ' EA ' + str(request.POST)) if name.private == True: return HttpResponseRedirect('/WhoZwho/editpc/' + nid + '/' + browser_tab) else: return HttpResponseRedirect('/WhoZwho/ename/' + nid + '/' + browser_tab) else: WZ['ErrorMessage'] = str(form.errors) else: if aid == '0': form = DirectoryEditAddressForm() else: form = DirectoryEditAddressForm(initial={ 'street': address.street, 'address_line2': address.address_line2, 'municipality': address.municipality, 'city': address.city, 'province': address.province, 'country': address.country, 'postcode': address.postcode, 'home_phone': address.phone, }) if aid == '0': EditAddressTitle = 'Add New Address:' else: EditAddressTitle = 'Edit Address: ' + address.street context = { 'EditAddressTitle': EditAddressTitle, 'aid': aid, 'browser_tab': WZ['Tabs'][WZ['ActiveTab']][2], 'form': form, 'nid': nid, 'WZ': WZ } context.update(csrf(request)) return render_to_response('DirectoryEditAddress.html', context )
def add_address(self, data): address = Address(**data) address.save() return address
(r'^login/$', 'newtest.login.login'), (r'^logout/$', 'newtest.login.logout'), (r'^wiki/$', 'newtest.wiki.views.index'), (r'^wiki/(?P<pagename>\w+)/$', 'newtest.wiki.views.index'), (r'^wiki/(?P<pagename>\w+)/edit/$', 'newtest.wiki.views.edit'), (r'^wiki/(?P<pagename>\w+)/save/$', 'newtest.wiki.views.save'), (r'^address/', include('newtest.address.urls')), # Uncomment this for admin: (r'^admin/', include('django.contrib.admin.urls')), ) if request.POST: post = request.POST new_address = Address( name = post["name"], number = post["number"], telephone = post["telephone"], Email = post["Email"], address = post["address"], QQ = post["QQ"], birthday = post["birthday"], ) new_address.save() urlpatterns = patterns('', # ... the rest of your URLconf goes here ... ) + static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)