def forwards(self, orm): # we need to associate each user to an account object for user in User.objects.all(): a = Account() a.user = user a.language = 'en' # default language a.save()
def create(request): if request.method == 'POST': # save new evento title = request.POST['title'] description = request.POST['description'] date_start = request.POST['date_start'] date_end = request.POST['date_end'] lat = request.POST['lat'] lng = request.POST['lng'] #image = request.FILES['image'] event = Event(title=title) event.last_update = datetime.datetime.now() event.description = description event.date_start = datetime.datetime.strptime(date_start, '%d/%m/%Y %H:%M') if not date_end: event.date_end = None else: event.date_end = datetime.datetime.strptime(date_end, '%d/%m/%Y %H:%M') event.location = [float(lat),float(lng)] user_id = request.session.get('userid') user = Account.objects(id=user_id)[0] event.user = user event.user_going = [user] #im = Image.open(image) #event.image.put(open(im)) event.save() Account.objects(id=user_id).update_one(push__event_going=event) return HttpResponseRedirect(reverse('event-list')) return render_to_response('event/event_create.html',{ 'request':request}, context_instance=RequestContext(request))
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {'user': user} if not username: return None warn_setting('SOCIAL_AUTH_CREATE_USERS', 'create_user') if not setting('SOCIAL_AUTH_CREATE_USERS', True): # Send signal for cases where tracking failed registering is useful. socialauth_not_registered.send(sender=backend.__class__, uid=uid, response=response, details=details) return None email = details.get('email') request = kwargs["request"] user = User.objects.create_user(username=username, email=email) Account.create(request=request, user=user) EmailAddress.objects.add_email(user, user.email, primary=True) return { 'user': user, 'is_new': True }
def import_banquepopulaire(data): """ Parsing des données Banque Populaire au format CSV Le format du fichier CSV proposé par la Banque Populaire est le suivant: Le séparateur par défaut est ';' (point virgule) Les champs disponibles sont: - N° du compte - Date de comptabilisation (au format JJ/MM/AAAA) - Date de l'opération (au format JJ/MM/AAAA) - Libellé - Référence - Date valeur (au format JJ/MM/AAAA) - Montant """ # Traitement par lignes des données for line in StringIO.StringIO(data): # Découpage des champs CSV csvdata = line.split(";") if len(csvdata) < 7: continue # On ignore la ligne d'en-tête du CSV (si il y en a une) if csvdata[0].isdigit() == False: continue # Date de l'opération date = datetime.datetime.strptime(csvdata[2], "%d/%m/%Y").date() # Montant de l'opération try: expense = float(csvdata[6]) except ValueError: expense = float(csvdata[6].replace(",", ".")) # Description de l'opération et catégorisation description = csvdata[3] subcategory = settings.subcategory_default # Modifications automatiques de la description et de la subcategory description = change_description(description) subcategory = change_subcategory(subcategory, description) # halve or not halve = halve_or_not("banquepopulaire", description) if halve is True: expense = expense / 2 account = Account( date=date, description=description, expense=expense, subcategory=subcategory, bank="banquepopulaire", check=False, halve=halve, ) account.save()
def account(request): # Get an account object account = request.account if not account: account = Account(user=request.user) account.put() # Setup the form initial = { "photo_backend": account.photo_backend, "site_title": account.site_title, "site_header": account.site_header, "thumb_size": account.thumb_size, "thumb_cropped": account.thumb_cropped, "full_size": account.full_size, "homepage_size": account.homepage_size, "homepage_album": account.homepage_album, "featured_albums": account.featured_albums, "service_username": account.service_username, "merchant_id": account.merchant_id, "analytics_id": account.analytics_id, } backend = account.backend try: albums = backend.get_all_albums() except Exception, e: # raise e albums = []
def __create_new_account__(self,email,user_data): """ We found a new account that does not exist in our database. Create a Django User from user email and the associated Account object. Password is automatically generated for the user. """ try: id = self.__extract_account_id__(user_data["resource_uri"]) new_user = Account.create_user(email,email, user_data["first_name"], user_data["last_name"], generate_password=True ) new_account = Account(ip_address=user_data[u'tr_ip_address'], email=email, imported=True, synched=False, name = "%s %s" % (user_data["first_name"],user_data["last_name"]), user = new_user, imported_date = dt.utcnow().replace(tzinfo=utc), external_id = id ) new_account.save() return True except Exception,e : print "Exception %s" % e return False
def delete(request, event_id): user_id = request.session.get('userid') user = Account.objects(id=user_id)[0] event = get_document_or_404(Event, id=event_id, user=user) Account.objects().update(pull__event_going=event) Account.objects().update(pull__event_maybe=event) event.delete() return HttpResponseRedirect(reverse('event-list'))
def get_account(request): if request.user and request.user.is_authenticated(): try: account = request.user.account_set.get() #get_profile() except ObjectDoesNotExist: user = request.user account = Account(user=user, name='%s %s' % (user.first_name, user.last_name)) account.save() return {'account' : account} return {'account' : None}
def import_oney(data): """ Parsing des données pour Oney """ form_list = [] # creation liste avec une ligne une dépense list_data = data.split("\n") for e in list_data: # une liste de chacun ligne est faite e_list = e.split("\t") # format_ex : [u'26/02/2015', u'PAYPAL - 0800 942 890 - traite le 27/02', u' ', u'45,80', u' \r'] if len(e_list) < 4: # si e_list a moins de 4 éléments dernier élément continue description = e_list[1].encode("utf-8") if "Solde initial" in description: continue if "Prélèvement mensualité" in description: continue if "Intérêts" in description: continue # on definit chaque valeur d'un objet Account # on définit la date comme un objet datetime date = datetime.datetime.strptime(e_list[0], "%d/%m/%Y").date() # l'id = la date + la depense ex: 201502264580 # description description = re.sub(r" - traité le .*$", "", description) description = re.sub(r" - [0-9 ]*PARIS[0-9 ]*$", "", description) # modification description description = change_description(description) # definition de subcategory subcategory = settings.subcategory_default subcategory = change_subcategory(subcategory, description) # expense : on récupère la dépense positive ou négtive if e_list[2] == " ": expense = float("-" + e_list[3].replace(",", ".")) elif e_list[3] == " ": expense = float(e_list[2].replace(",", ".")) # halve or not halve = halve_or_not("oney", description) if halve is True: expense = expense / 2 account = Account( date=date, description=description.decode("utf-8"), expense=expense, subcategory=subcategory, bank="oney", check=False, halve=halve, ) account.save()
def user_post_save(sender, **kwargs): """ After User.save is called we check to see if it was a created user. If so, we check if the User object wants account creation. If all passes we create an Account object. We only run on user creation to avoid having to check for existence on each call to User.save. """ user, created = kwargs["instance"], kwargs["created"] disabled = getattr(user, "_disable_account_creation", not settings.ACCOUNT_CREATE_ON_SAVE) if created and not disabled: from account.models import Account Account.create(user=user)
def login_to_account(request): user = users.get_current_user() if user: request.session['user_email'] = user._User__email a = Account.objects.filter(email = user._User__email) if a.count()==0: a = Account(username = user.nickname(), email = user._User__email) a.save() else: a=a[0] request.session['user'] = a.id return HttpResponseRedirect('/') else: return HttpResponseRedirect(users.create_login_url('/accounts/login'))
def regist(request): if request.method == 'POST': form = SigninForm(request.POST) if form.is_valid(): value = form.cleaned_data user = User(email=value['email'],username = value['email'],password = value['password']) user.save() account = Account(user=user,nickname = value['nickname']) account.save() request.session['usr'] = account return render_to_response('account/welcome.html',{'nickname':value['nickname']},context_instance=RequestContext(request)) else: form = SigninForm() return render_to_response('account/regist.html',{'form':form},context_instance=RequestContext(request))
def tweets(): tweets = [] for tweet in tweepy.Cursor(api.search, q='ISIS', rpp=100).items(100): latitude = None longitude = None if tweet.geo: latitude = None longitude = None #latitude = tweet.geo.latitude #longitude = tweet.geo.longitude print dir(tweet) print '='*80 print dir(tweet.author) print '='*80 accounts = Account.objects.filter(account_id=tweet.author.id_str) if accounts.count(): account = accounts.first() else: tAccount = tweet.author account = Account( account_id=tAccount.id_str, description=tAccount.description, favourites_count=tAccount.favourites_count, followers_count=tAccount.followers_count, geo_enabled=tAccount.geo_enabled, location=tAccount.location, name=tAccount.name, screen_name=tAccount.screen_name, url=tAccount.url, verified=tAccount.verified ) account.save() tweets.append(Tweet( tweet_id=tweet.id_str, place=tweet.place, latitude=latitude, longitude=longitude, created_at=tweet.created_at, text=tweet.text, retweet_count=tweet.retweet_count, retweeted=tweet.retweeted, favorite_count=tweet.favorite_count, favorited=tweet.favorited, account=account )) Tweet.objects.bulk_create(tweets)
def eventGoing(request): user = Account.objects(id=request.session.get('userid'))[0] events = Event.objects(user_going__in=[user]) return render_to_response('event/event_list_readonly.html', { 'event_list': events, 'request':request }, context_instance=RequestContext(request))
def account(request): ctx = { "account": Account.for_request(request), "ACCOUNT_OPEN_SIGNUP": settings.ACCOUNT_OPEN_SIGNUP, "ACCOUNT_CONTACT_EMAIL": settings.ACCOUNT_CONTACT_EMAIL, } return ctx
def detail(request, event_id): event = get_document_or_404(Event, id=event_id) if event.date_start: event.date_start = event.date_start.strftime('%d/%m/%Y %H:%M') if event.date_end: event.date_end = event.date_end.strftime('%d/%m/%Y %H:%M') if event.location: event.lat = event.location[0] event.lng = event.location[1] if request.session.get('userid'): template = 'event/event_detail.html' user = Account.objects(id=request.session.get('userid'))[0] event.going = Event.objects(user_going__in=[user], id=event_id) event.going = 'active' if event.going else '' event.maybe = Event.objects(user_maybe__in=[user], id=event_id) event.maybe = 'active' if event.maybe else '' event.decline = Event.objects(user_decline__in=[user], id=event_id) event.decline = 'active' if event.decline else '' else: template = 'event/event_detail_nologin.html' params = {'event':event, 'request':request} return render_to_response(template, params, context_instance=RequestContext(request))
def move_prayerbook_item(request, item_id): if request.method == 'GET': account = Account.get_account(request) if account: prayer_book = account.prayerbook item = get_object_or_404(PrayerBookItem, pk=item_id) items = prayer_book.prayerbook_items.all() if item in items: direction = request.GET.get('direction', None) if direction == 'up' and item.index > 1: prev_item = items.filter(index=item.index - 1) if prev_item: prev_item = prev_item[0] prev_item.index = item.index prev_item.save() item.index = item.index - 1 item.save() return HttpResponse(json.dumps({'status': True, 'message': u'Молитва перемещена вверх'}), 'json') elif direction == 'down': next_item = items.filter(index=item.index + 1) if next_item: next_item = next_item[0] next_item.index = item.index next_item.save() item.index = item.index + 1 item.save() return HttpResponse(json.dumps({'status': True, 'message': u'Молитва перемещена вниз'}), 'json') return HttpResponse(json.dumps({'status': False, 'message': u'Молитва не перемещена'}), 'json')
def get_context_data(self, **kwargs): context = super(self.__class__, self).get_context_data(**kwargs) account = Account.get_account(self.request) prayerbook = account.prayerbook context['account'] = account context['pray_in_my_praybook'] = prayerbook.pray_added(super(self.__class__, self).get_object()) return context
def delete(account): encoded_key = request.args["account"] acc = ndb.Key(urlsafe=encoded_key) acc.delete() flash(u"Account deleted!") return render_template("account/accounts.html", account=account, accounts=Account.query())
def server_expired(): server = get_server(request.form['server']) sender = 'no-reply@' + get_application_id() + '.appspotmail.com' site_url = 'http://' + get_application_id() + '.appspot.com' for account in Account.query(): message = mail.EmailMessage(sender=sender, to=account.email) message.subject = "Server expire notification: %s" % server.server_name show_url = url_for('server.show', server_key=server.key.urlsafe()) message_body = "Server %s is expired at %s\n %s%s" \ % (server.server_name, server.expire_date, site_url, show_url) if server.blocked: url = 'http://%s/manager/expired/%s'\ % (server.ip_address, server.token) result = fetch_server_url(url=url, retry_count=3) if result.status_code == 200: if result.content == 'TRUE': message_body += '\n Server %s is blocked upon expiry, %s'\ % (server.server_name, server.expire_date) else: message_body += '\n %s' % result.content else: message_body += '\n Unable to reach %s to block upon expiry, %s'\ % (server.server_name, server.expire_date) message.body = message_body message.send() return make_response('')
def list(request): # Get all events from DB user = Account.objects(id=request.session.get('userid'))[0] events = Event.objects(user=user) return render_to_response('event/event_list.html', {'event_list': events, 'request':request}, context_instance=RequestContext(request))
def get_context_data(self, **kwargs): context = super(RequestView, self).get_context_data(**kwargs) account = Account.get_account(self.request) context['pray_event_form'] = PrayEventForm(initial={'request': self.object, 'prayer': account}) context['comment_form'] = CommentForm(initial={'request': self.object, 'account': account}) context['form'] = RequestForm(initial={'account': account}) context['account'] = account return context
def post(self, request, *args, **kwargs): account_form = AccountForm(request.POST) if account_form.is_valid(): #user = account_form.cleaned_data['user'] #user = self.request.user name = account_form.cleaned_data['name'] amount = account_form.cleaned_data['amount'] active = account_form.cleaned_data['active'] #account = Account(user=user, name=name, amount=amount, active=active) account = Account(user=self.request.user, name=name, amount=amount, active=active) account.save() return HttpResponseRedirect('/') else: context = {'account_form': account_form} return render(request, self.template_name, context)
def sign_up(request): account = Account.create_raw_account(request) if account: message = render_to_string('account/signup_email.html', {'account': account}) account.user.email_user(u'Запрошена реистрация на сайте', message) return HttpResponse(json.dumps( {'message': u'Для продолжения регистрации перейдтие по ссылке, которая отправлена на указанную почту'}), 'json') else: return HttpResponse(json.dumps({'message': u'Пользователь с таким адресом уже существует'}), 'json')
def setUp(self): self.account = Account(email='*****@*****.**', password='******') self.account.first_name = 'user1' self.account.last_name = 'mail' self.account.is_active = True now = datetime.datetime.now() self.account.created_at = now self.account.updated_at = now self.account.save()
def add_pray_to_prayerbook(request, pray_id): pray = get_object_or_404(Pray, pk=pray_id) account = Account.get_account(request) prayerbook = account.prayerbook item = prayerbook.add_pray(pray) if item: return HttpResponse(json.dumps({'status': True, 'message': u'Молитва добавлена в молитвослов'}), 'json') return HttpResponse(json.dumps({'status': False, 'message': u'Вы уже добавили эту молитву в свой молитвослов'}), 'json')
def make_account(self, level=1, people=1): """ Utility method: creates an account with a specific subscription level and # people """ account = Account( subscription_level_id = level, ) account.save() for i in range(people): account.person_set.create( username = '******' % i, password = '******' % i, first_name = 'first_name %i' % i, last_name = 'last_name %i' % i, email = '*****@*****.**' % i, ) return account
def import_boobank(data, bank): """ Parsing des données Boobank Le format die boobank est le suivant: Le séparateur par défaut est ' ' (point virgule) Les champs disponibles sont: - Date de l'opération (au format AAAA-MM-JJ) : 1-10 champs - Category : 14-25 - Label : 27-78 - Montant : 80-89 """ # Traitement par lignes des données for line in StringIO.StringIO(data): # Date de l'opération try: date = datetime.datetime.strptime(line[1:11], "%Y-%m-%d").date() except: continue # Montant de l'opération expense = float(line[80:90]) # Description de l'opération et catégorisation description = line[27:79] # Modifications automatiques de la description et de la subcategory description = change_description(description) subcategory = categories.utils.autoset_category(description) # halve or not halve = halve_or_not(bank, description) if halve is True: expense = expense/2 account = Account( date = date, description = description, expense = expense, category = subcategory, bank = bank, check = False, halve = halve ) account.save()
def login_return(request, backend_name): backend = get_backend(backend_name) redirect_url = request.session.get('post_login_redirect', '/') return_url = "http://%s%s" % (settings.MAIN_HOST, reverse('login_return', args=[backend_name])) try: access_token = backend.get_token(request, return_url) except DenyException: return HttpResponseRedirect(redirect_url) except: return _error_page(request) user_data = backend.get_user_data(access_token) account = Account.objects.filter(id_from_backend=user_data['id'], backend=backend_name, ) if account.count(): account = account[0] user = account.user user = authenticate(username=user.username, password=2) login(request, user) return HttpResponseRedirect(redirect_url) if not request.user.is_authenticated(): un = "%s - %s" % (user_data['screen_name'], user_data['id']) un = un[:30] user, created = User.objects.get_or_create(username=un) if created: temp_password = User.objects.make_random_password(length=12) user.set_password(temp_password) user.first_name = user_data['name'] user.save() user = authenticate(username=user.username, password=2) else: user = request.user account = Account(user=user, name=user.first_name, img_url=user_data['picture'], backend=backend_name, id_from_backend=user_data['id'], ) account.save() login(request, user) return HttpResponseRedirect(redirect_url)
def post(self, request, *args, **kwargs): account = Account.get_account(request) item = super(self.__class__, self).get_object() if item not in account.prayerbook.prayerbook_items.all(): return self.json_fail_response(message=u'Вы можете молитвы только из своего молитвослова') if 'delete' in request.POST: item.delete() return self.json_success_response(message=u'Молитва удалена') else: return self.json_fail_response(message=u'Отмена удаления')
def create(self, validated_data): account = Account.create(**validated_data) account.save() return account
class AccountTestCase(TestCase): def setUp(self): self.account = Account(username="******", email="*****@*****.**") self.account.set_password("b#891") self.account.save() def test_string_representation(self): account = Account(username="******") self.assertEqual(str(account), account.username) #@skip("Don't want to test") def test_login(self): response = self.client.get('/account/login') self.assertEqual(response.status_code, 200) def test_register(self): response = self.client.get('/account/register') self.assertEqual(response.status_code, 200) def test_successful_login(self): password = "******" account = Account(username="******", first_name="", last_name="", email="") account.set_password(password) account.save() response = self.client.post(reverse('account:login'), {'username': "******", 'password': password}) # self.assertEqual(response.status_code, 302) messages = list(get_messages(response.wsgi_request)) self.assertEqual(str(messages[0]), 'Login successful') # self.assertRedirects(response, reverse('home:dashboard'), status_code=302, # target_status_code=200, msg_prefix='', fetch_redirect_response=True) def test_login_invalid_credentials(self): response = self.client.post(reverse('account:login'), {'username': "******", 'password': "******"}) self.assertEqual(response.status_code, 302) messages = list(get_messages(response.wsgi_request)) self.assertEqual(str(messages[0]), "Invalid username or password") self.assertEqual(messages[0].level, ERROR) self.assertRedirects(response, reverse('account:login'), status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True) def test_successful_registration(self): response = self.client.post(reverse('account:register'), {'username': "******", 'first_name': 'Mark', 'last_name': 'Johnson', 'email': '*****@*****.**', 'password': '******', 'password_confirmation': '24r4^j'}) self.assertEqual(response.status_code, 302) messages = list(get_messages(response.wsgi_request)) self.assertEqual(str(messages[0]), 'Account registration successful') self.assertEqual(messages[0].level, SUCCESS) self.assertRedirects(response, reverse('account:register'), status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True) def test_successful_registration_missing_fields(self): """Test for registration when email, first name and last name are not provided""" response = self.client.post(reverse('account:register'), {'username': "******", 'first_name': '', 'last_name': '', 'email': '', 'password': '******', 'password_confirmation': '24r4383'}) self.assertEqual(response.status_code, 302) messages = list(get_messages(response.wsgi_request)) self.assertEqual(str(messages[0]), 'Account registration successful') self.assertEqual(messages[0].level, SUCCESS) self.assertRedirects(response, reverse('account:register'), status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True)
def create_account(self): return Account.create(request=self.request, user=self.created_user, create_email=False)
def reset_items(request): BuyerItem.objects.all().delete() Items.objects.all().delete() # create dummy account try: a = Account.objects.get( facebook_id="1020420", display_name="Goodwill Industries", email="*****@*****.**" ) except Account.DoesNotExist: a = Account( facebook_id="1020420", display_name="Goodwill Industries", email="*****@*****.**", user_location="39.417672,-87.330438", ) a.save() # create dummy device try: d = Device.objects.get_or_create( uuid = "E6264D84-C395-4132-8C63-3EF051480191", account_id= a, apns_token = "<224c36d9 4de49676 27c42676 ee3ba0a3 33adf555 79259e36 182abf83 8b86a35b>", ip_address = "000.000.000.00", notifications_enabled = True, auth_token = "asdfasdfasdfasdf_{}".format(a.id), app_version = "16" )[0] d.save() except Account.DoesNotExist: d = Device( uuid = "E6264D84-C395-4132-8C63-3EF051480191", account_id= a, apns_token = "<224c36d9 4de49676 27c42676 ee3ba0a3 33adf555 79259e36 182abf83 8b86a35b>", ip_address = "000.000.000.00", notifcations_enabled = True, auth_token = "asdfasdfasdfasdf_{}".format(a.id), app_version = "16" ) d.save() i = Items( image_urls = "https://app.bakkle.com/img/b83bdbd.png", title = "Orange Push Mower", description = "Year old orange push mower. Some wear and sun fadding. Was kept outside and not stored in shed.", location = "39.417672,-87.330438", seller = a, price = 50.25, tags = "lawnmower, orange, somewear", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/WP_20150417_09_47_27_Pro.jpg", title = "Oil change", description = "will change your cars oil at your location, $ 19.95.", location = "39.417672,-87.330438", seller = a, price = 19.95, tags = "service, oil change", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00e0e_5WQCcunAcn_600x450.jpg", title = "Flat screen LED TV", description = "Flat screen LED LCD TV. Brand new in box, 4 HDMI ports and Netflix built in.", location = "39.417672,-87.330438", seller = a, price = 107.00, tags = "tv, led, netflix", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00n0n_eerJtWHsBKc_600x450.jpg", title = "15\" MacBook pro", description = "MacBook Pro 15\" Mid 2014 i7. 2.2 GHz, 16 GB RAM, 256 GB SSD. Very little use, needed a lighter model so switched to MacBook air. Includes original box, power cord, etc.", location = "39.417672,-87.330438", seller = a, price = 999.00, tags = "mac, apple, macbook, macbook pro", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00n0n_gonFpgUcRAe_600x450.jpg", title = "Paint ball gun", description = "Gun only, no CO2 tank. Needs new HPR piston", location = "39.417672,-87.330438", seller = a, price = 40.99, tags = "paintball, gun, bump paintball", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00O0O_kOqfijcw7FL_600x450.jpg", title = "Business law text book", description = "Business law text and cases, clarkson, miller, jentz, 11th edition. No marks or highlighting.", location = "39.417672,-87.330438", seller = a, price = 40.99, tags = "textbook, business law", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00P0P_dcFyXMBIkYE_600x450.jpg", title = "Baseball mitt", description = "Louisville slugger baseball mitt, mint condition.", location = "39.417672,-87.330438", seller = a, price = 30.00, tags = "baseball mitt", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00s0s_49F9D9EnAJ3_600x450.jpg", title = "Bicycle", description = "Pure fix fixie bicycle.", location = "39.417672,-87.330438", seller = a, price = 300, tags = "bicycle", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00T0T_f1xeeb2KYxA_600x450.jpg", title = "Canon 50D", description = "Canon 50D digital camera. Comes with f1.8 50mm lens.", location = "39.417672,-87.330438", seller = a, price = 30.00, tags = "canon, 50d, digital camera", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00u0u_hj2g60Tn2D7_600x450.jpg", title = "iPhone 5", description = "White Apple iphone 5. Unlocked", location = "39.417672,-87.330438", seller = a, price = 200.00, tags = "apple, iphone, iphone 5", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00V0V_kQXPgLCzkEl_600x450.jpg", title = "weights", description = "Premium adjustable hand barbell weight set.", location = "39.417672,-87.330438", seller = a, price = 300.00, tags = "weights, barbell", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00W0W_hCYzWAyYAvP_600x450.jpg", title = "Blender", description = "Blender, used. Runs great. 5 speeds with turbo", location = "39.417672,-87.330438", seller = a, price = 12.00, tags = "blender", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00404_8sCApbm5Bvc_600x450.jpg", title = "Playstation 2", description = "Playstation 2 with controller. Broken, needs laser cleaning. Won't read discs.", location = "39.417672,-87.330438", seller = a, price = 45.00, tags = "sony, playstation, controller", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00808_k0TscttMik5_600x450.jpg", title = "Baseball bat", description = "Basic home security system.", location = "39.417672,-87.330438", seller = a, price = 10.00, tags = "baseball, security, bat", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/00909_iVAvBfYmpNm_600x450.jpg", title = "Gas grille", description = "Propane barbeque grill with side burner. 2 years old worth $200 from Lowes. Full propane bottle included.", location = "39.417672,-87.330438", seller = a, price = 10.00, tags = "propane, gas, grille, barbeque, bbq", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now(), times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/01313_fXdf3fNJDJC_600x450.jpg", title = "Marketing textbooks", description = "MKTG marketing text (instructor edition) by Lam, hair, mcdaniel and Essentials of Entrepreneurship and Small Business Management by Normal M. Scarborough (7th global edition).", location = "39.417672,-87.330438", seller = a, price = 175.00, tags = "marketing, textbooks", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/01313_gsH7Yan7PYA_600x450.jpg", title = "Nike shoes", description = "Nike women's air max shoes size 6 1/2. Never worn outside.", location = "39.417672,-87.330438", seller = a, price = 90.00, tags = "shoes, nike, womens", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/b8348df.jpg", title = "Rabbit Push Mower", description = "Homemade lawn mower. Includes rabbit and water container.", location = "39.417672,-87.330438", seller = a, price = 10.99, tags = "lawnmower, homemade, rabbit", method = Items.PICK_UP, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() i = Items( image_urls = "https://app.bakkle.com/img/b8349df.jpg", title = "iPhone 6 Cracked", description = "iPhone 6. Has a cracked screen. Besides screen phone is in good condition.", location = "39.417672,-87.330438", seller = a, price = 65.99, tags = "iPhone6, cracked, damaged", method = Items.DELIVERY, status = Items.ACTIVE, post_date = datetime.datetime.now() times_reported = 0 ) i.save() print("Adding {}".format(i.title)) return HttpResponse("resetting {}".format(i.title)) #change success value
def __init__(self, *args, **kwargs): super(AccountForm, self).__init__(*args, **kwargs) try: self.account = Account.objects.get(user=self.user) except Account.DoesNotExist: self.account = Account(user=self.user)
#!/usr/bin/env python # -*- coding: utf-8 -*- from account.models import Account from django.contrib.auth.models import User users = User.objects.all() for user in users: try: Account.objects.get(user=user) except Account.DoesNotExist: Account(user=user).save()
def setUp(self): self.account = Account(username="******", email="*****@*****.**") self.account.set_password("b#891") self.account.save()
def mutate(_, info, email): sid = transaction.savepoint() try: account = Account.get_account({'email': email, 'is_active': True}) if account is None: return ResetPassword(success=False, errors=[ ErrorsType(field='email', message='アカウントが存在しません。') ]) uuid_token = uuid.uuid4() account.password_token = uuid_token account.save() serialized_token = serializer_time_dumps( str(uuid_token), expires=time_seconds(days=1)) try: domain = info.context.get_host() except: domain = '' email_message = EmailMessage( subject='パスワード再発行', from_email='BASYO KASHI<*****@*****.**>', to=[email], body=""" <h3>変更手続きをしてください。</h3> <p><a href="https://{domain}/password/{token}"> https://{domain}/password/{token}</a></p> <p>有効期間は発行から24時間以内で登録ください。</p> """.format(domain=domain, token=str(serialized_token))) email_message.content_subtype = 'html' email_result = email_message.send() if email_result != 0: transaction.savepoint_commit(sid) return ResetPassword(success=True, send_token=str(serialized_token)) else: transaction.savepoint_rollback(sid) return ResetPassword(success=False, errors=[ ErrorsType(field='send email', message='Eメールが送れませんでした。') ]) except Exception as e: transaction.savepoint_rollback(sid) return ResetPassword( success=False, errors=[ErrorsType(field='email', message=str(e))])
def create_account(self, new_user, form): return Account.create(request=self.request, user=new_user, create_email=False)
def account(request): ctx = { "account": Account.for_request(request), "ACCOUNT_OPEN_SIGNUP": settings.ACCOUNT_OPEN_SIGNUP, } return ctx
def test_string_representation(self): account = Account(username="******") self.assertEqual(str(account), account.username)
def post(request): Account.remove(request.user.username) return Response({'detail': 'account hash been deleted'}, status=status.HTTP_201_CREATED)
def unfollow(request, username): if request.method == 'POST': owner = Account.get_by_user(request.user) follow = Account.get_by_username(username) owner.unfollow(follow) return redirect('profile', username)
if sender.name == 'facebook' and 'image/gif' in str( content.info()): return filename = user.username + "_profile" + '.' + content.headers.subtype profile.photo.save(filename, ContentFile(content.read())) except IOError, e: logger.debug(e) try: profile.language = response.get('locale').split("_")[0] profile.full_clean() except Exception: pass profile.time_zone = response.get('timezone') profile.save() account = user.account_set.all()[0] or Account.create(user=user, create_email=False) try: account.language = response.get('locale').split("_")[0] tz_offset = int(response.get('timezone')) tz_joiner = "" if tz_offset < 0 else "+" account.timezone = coerce_timezone_value( tz_joiner.join(("Etc/GMT", str(tz_offset)))) account.full_clean() except Exception: pass account.save() email, created = EmailAddress.objects.get_or_create(user=user, email=user.email) email.verified = True email.save() return True
def account_list(request): if request.method == 'GET': queryset = Account.objects.all().order_by('-id') query = request.GET.get("q") if query: queryset = queryset.filter( Q(first_name__icontains=query) ).distinct() paginator = Paginator(queryset, 2) # Show 25 contacts per page page = request.GET.get('page') contacts = paginator.get_page(page) serializer = AccountSerializer(contacts, many=True) return Response(serializer.data) elif request.method == 'POST': user_serializer = UserSerializer(data=request.data) if user_serializer.is_valid(): # user_serializer.save() user = User() user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.password = make_password(request.POST.get('password'), None) user.username = request.POST.get('username') user.email = request.POST.get('email') user.date_joined = request.POST.get('date_joined') user.save() profile = Account() profile.user = user profile.organization = Organization.objects.get(id=1) profile.mobile = request.POST.get('mobile') profile.full_name = request.POST.get( 'first_name') + " " + request.POST.get('last_name') profile.start_date = request.POST.get('start_date') profile.end_date = request.POST.get('end_date') profile.user_role = request.POST.get('user_role') profile.user_picture = "test" profile.gender = request.POST.get('gender') profile.save() return Response(user_serializer.data, status=status.HTTP_201_CREATED)