def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" # TODO 2 # step 1: make sure user is authed # uncomment the following lines: user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException("Authorization required") p_key = ndb.Key(Profile, getUserId(user)) profile = None # step 2: create a new Profile from logged in user data # you can use user.nickname() to get displayName # and user.email() to get mainEmail profile = p_key.get() if not profile: profile = Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() return profile # return Profile
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" # noqa user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # Get user id by calling getUserId(user) user_id = getUserId(user) # Create a new key of kind Profile from the id. p_key = ndb.Key(Profile, user_id) # Get the entity from datastore by using get() on the key profile = p_key.get() # If profile doesn't exist, we create a new one if not profile: profile = Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) # Save the profile to datastore profile.put() return profile # return Profile
def getSessionsInWishlist(self, request): """Query for all sessions in a conference that the user is interested in.""" # Get current user user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization is required') # Get profile of user from Profile datastore user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) profile = p_key.get() # Create new Profile if it does not exist already if not profile: profile = Profile( key = p_key, displayName = user.nickname(), mainEmail= user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() sess_keys = [ndb.Key(urlsafe=ses) for ses in profile.SessionsInWishlist] sessions = ndb.get_multi(sess_keys) # return set of SessionForm objects per Session return SessionForms( items=[self._copySessionToForm(sess) for sess in sessions] )
def signup(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user( username=form.cleaned_data['username'], password=form.cleaned_data['password1'], email=form.cleaned_data['email'] ) user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) profile = Profile( first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], user=user) profile.save() login(request, user) msg = ("Thanks for registering! You are now logged in and ready to " "go questing.") messages.info(request, msg) return HttpResponseRedirect(reverse('quest_maker_app:homepage')) else: form = RegistrationForm() variables = RequestContext(request, {'form': form}) return render_to_response('registration/signup.html', variables)
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # TODO 1 # step 1. copy utils.py from additions folder to this folder # and import getUserId from it # step 2. get user id by calling getUserId(user) # step 3. create a new key of kind Profile from the id user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) # TODO 3 # get the entity from datastore by using get() on the key profile = p_key.get() if not profile: profile = Profile( key=p_key, # TODO 1 step 4. replace with the key from step 3 displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) # TODO 2 # save the profile to datastore profile.put() return profile # return Profile
def register(request): next = request.GET.get('next', '/') if request.method == "POST": form = RegisterForm(request.POST, request.FILES) if form.is_valid(): username = form.cleaned_data["username"] email = form.cleaned_data["email"] password = form.cleaned_data["password"] try: file_obj = request.FILES['avatar'] url = make_avatar(file_obj) except: url = '' next = request.POST["next"] if next == 'None': next = '/' user = User.objects.create_user(username, email, password) profile = Profile(user=user, avatar=url, today=today) profile.save() user.save() return HttpResponseRedirect("/account/login/?f=register&next=%s" % next) else: form = RegisterForm() return render_to_response("account/register.html",{'form': form, 'next': next},\ context_instance=RequestContext(request))
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" # step 1: make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get user id by calling getUserId(user) user_id = getUserId(user) logging.debug( "user_id is: " ) logging.debug( user_id ) # create a new key of kind Profile from the id profile_key = ndb.Key(Profile, user_id) # get entity from datastore by using get() on the key profile = profile_key.get() # create a new Profile from logged in user data # use user.nickname() to get displayName # and user.email() to get mainEmail if not profile: profile = Profile( userId = None, key = profile_key, displayName = user.nickname(), mainEmail = user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) # save new profile to datastore returned_profile_key = profile.put() print "returned_profile_key is: " print returned_profile_key return profile
def register(request): form = UserRegistrationForm(request.POST) if form.is_valid(): #TODO Add functionality to save email = form.cleaned_data['email'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] password = form.cleaned_data['password'] password_again = form.cleaned_data['password_again'] if password != password_again: return my_render(request, 'books/signup.html', {'form': UserRegistrationForm(), 'message': 'passwords did not match' }) elif len(User.objects.filter(username = email)): return my_render(request, 'books/signup.html', {'form': UserRegistrationForm(), 'message': 'ERROR: email already exists' }) elif "" in [email, first_name, last_name, password, password_again]: return my_render(request, 'books/signup.html', {'form': UserRegistrationForm(), 'message': 'all fields should be filled' }) else: user = User.objects.create_user(username = email, email=None, password=password, last_name=last_name, first_name=first_name) user.save() a = Profile(user = user, name = user.first_name + " " + user.last_name, email = user.username) a.save() user = authenticate(username=email, password =password) login(request, user) context = {'user': request.user} return my_render(request, 'books/homepage.html', context)
def register(request): if request.method == 'POST': span = {1:False} form = NewUserForm(request.POST) if form.is_valid(): new_user = form.save() user = auth.authenticate( email=request.POST.get('email', ''), password=request.POST.get('password1','')) if user is not None: auth.login(request, user) profile = Profile(user=user) profile.save() settings = Settings(user=user) settings.save() return HttpResponseRedirect("/create/profile/") else: span[1] = True form = NewUserForm() else: form = NewUserForm() span = {1:False} return render(request, "registration/register.html", { 'form': form, 'span': span })
def _getProfileFromUser(self): """Return user Profile from DataStore or create add new one if non-existent.""" # Getting and Verifying current user user = getUser() # get the user_id (email) user_id = getUserId(user) # Creating a profile key. p_key = ndb.Key(Profile, user_id) # Using the profile key to get a profile Object profile = p_key.get() # create new Profile if not there if not profile: profile=Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),) profile.put() return profile
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get Profile from datastore user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) profile = p_key.get() # create new Profile if not there if not profile: profile = Profile( key = p_key, displayName = user.nickname(), mainEmail= user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) w_id = Wishlist.allocate_ids(size=1, parent=p_key)[0] w_key = ndb.Key(Wishlist, w_id, parent=p_key) wishlist = Wishlist( key = w_key, sessionKeys = [] ) profile.put() wishlist.put() return profile # return Profile
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" # TODO 2 # step 1: make sure user is authed # uncomment the following lines: user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') p_key = ndb.Key(Profile, getUserId(user)) profile = None # step 2: create a new Profile from logged in user data # you can use user.nickname() to get displayName # and user.email() to get mainEmail profile = p_key.get() if not profile: profile = Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() return profile # return Profile
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" #make sure user is authenticated user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get user_id via the helper function in utils user_id = utils.getUserId(user) #generate a p_key for this user using the user_id p_key = ndb.Key(Profile, user_id) #get the profile associated with this p_key profile = p_key.get() if not profile: profile = Profile( key = p_key, displayName = user.nickname(), mainEmail= user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() #save profile to datastore return profile # return Profile
def profile_edited(request): user = request.user username = user.username tagline = request.POST.get("tagline") location = request.POST.get("location") interests = request.POST.getlist("interests[]") other_interests = request.POST.get("other_interests") skills = request.POST.getlist("skills[]") # other_skills = request.POST.get('other_skills') resources = request.POST.getlist("resources[]") # other_resources = request.POST.get('other_resources') wdywtd = request.POST.get("wdywtd") needs = request.POST.get("needs") offerings = request.POST.get("offerings") ideal_collaboration = request.POST.get("ideal_collaboration") profile = Profile( username=username, tagline=tagline, location=location, other_interests=other_interests, wdywtd=wdywtd, needs=needs, offerings=offerings, ideal_collaboration=ideal_collaboration, ) for cat in interests: setattr(profile, cat, True) for ski in skills: setattr(profile, ski, True) for res in resources: setattr(profile, res, True) profile.save() redirect_url = "/profile/%s" % (username) return redirect(redirect_url)
def save(self, user): try: data = user.get_profile() except: data = Profile(user=user) data.city = self.cleaned_data["city"] data.save()
def newProfile(): if request.method == 'POST': newProfile = Profile(name=request.form['name'], weight=request.form['weight'], gender=request.form['gender'], picture=random.choice(puppy_images), dateOfBirth=datetime.strptime( request.form['birthday'], "%Y-%m-%d"), description=request.form['description'], specialNeeds=request.form['needs']) session.add(newProfile) new_puppy = Puppy(shelter_id=randint(1, 5), profile=newProfile) session.add(new_puppy) session.commit() flash("New puppy and profile created!") return redirect(url_for('viewProfile', key=newProfile.id)) else: return render_template('new.html', viewType="profile", traits=Profile.defaultTraits())
def get_profiles(): """Fetches some JSON and saves it in the database.""" if request.method == "POST": # Get some JSON r = requests.get("https://api.github.com/users/{}".format(request.form["username"])) # Make sure we got some JSON back if r.status_code != 200: flash("That username didn't work. Please try again.") return redirect(url_for(profiles)) # Load the JSON into a Python dict profile_dict = r.json() # Create a new Profile object with Mongoengine, passing in the dict profile_object = Profile(raw_json=profile_dict) profile_object.save() # Prepare a message for the user flash("Saved a new profile.") # Redirect back to the profile list return redirect(url_for("profiles")) else: flash("That URL only accepts POST requests.") return redirect(url_for("profiles"))
def handle_join(request): # Handle request here vkuser = request.session.get('vk_user') errors = {} phone = request.REQUEST.get('phone') email = request.REQUEST.get('email') if phone: if not phone_validate(phone): errors["phone_error"] = u'Введите правильный телефон' else: errors['phone_error'] = u'Это поле не должно быть пустым' if email: if not email_validate(email): errors['email_error'] = u'Введите корректный e-mail' else: errors['email_error'] = u'Это поле не должно быть пустым' if errors: ec = {'vkuser': vkuser, 'email': email, 'phone': phone} ec.update(errors) return render_to_response('joinus.html', ec, context_instance=RequestContext(request)) else: p = Profile(name=' '.join([vkuser.first_name, vkuser.last_name]), vkontakte_id=vkuser.uid, email=email, phone=phone, photo=vkuser.photo, photo_medium=vkuser.photo_medium, status=u'Игрок') p.save() return redirect('/thankyou/')
def _get_profile_from_user(self): """Return user Profile from datastore, creating new one if non-existent.""" # Make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # Try to retrieve an existing profile... user_id = get_user_id(user) key = ndb.Key(Profile, user_id) profile = key.get() # ... and if not exists, create a new Profile from logged in user data if not profile: profile = Profile( userId=user_id, key=key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) # Create the profile in datastore profile.put() return profile
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" ## step 1: make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException("Authorization required") user_id = getUserId(user) # Create an instance of a Key for an id(user email) of a kind(Profile) p_key = ndb.Key(Profile, user_id) # Get the entity(user profile) associated with the key profile = p_key.get() # If the entity does not exist, create a new entity and put in datastore if not profile: profile = Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) # put will store profile as a persistent entity in the Datastore profile.put() return profile
def edit_object(self, object_to_edit: Profile, data: dict, current_user: User, **kwargs) -> Profile: object_to_edit.name = data['name'] object_to_edit.coffee_strength_in_percent = data[ 'coffee_strength_in_percent'] object_to_edit.water_in_percent = data['water_in_percent'] return object_to_edit
def add_or_update_profile_callback(room, event): username = event['sender'] args = event['content']['body'].split() profile_name = args[1] profile_phone = args[2] profile_password = args[3] # TODO проверка, есть ли уже профиль с введенными данными. # TODO Если есть - вывести сообщение и return user = User.get_or_create(username=username)[0] profile = Profile.get_or_none(Profile.owner == user, Profile.name == profile_name) if profile: profile.phone_number = profile_phone profile.password = profile_password profile.save() else: profile = Profile.create(owner=user, name=profile_name, phone_number=profile_phone, password=profile_password) current_profile = CurrentProfile.get_or_none(user=user) if current_profile: current_profile.profile = profile current_profile.save() else: current_profile = CurrentProfile.create(user=user, profile=profile) connection = UmsConnection(profile_phone, profile_password) CONNECTIONS.append((profile, connection)) captcha = connection.get_captcha() url = BOT.client.upload(captcha, 'image/png') room.send_text('Профиль добавлен, введите капчу командой captcha <key>') room.send_image(url, 'captcha.png')
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent. """ # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException( 'Authorization required') user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) profile = p_key.get() # create new Profile if not there if not profile: profile = Profile( key = p_key, displayName = user.nickname(), mainEmail= user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED)) profile.put() # return Profile return profile
def handle_join(request): # Handle request here vkuser = request.session.get('vk_user') errors = {} phone = request.REQUEST.get('phone') email = request.REQUEST.get('email') if phone: if not phone_validate(phone): errors["phone_error"] = u'Введите правильный телефон' else: errors['phone_error'] = u'Это поле не должно быть пустым' if email: if not email_validate(email): errors['email_error'] = u'Введите корректный e-mail' else: errors['email_error'] = u'Это поле не должно быть пустым' if errors: ec = {'vkuser': vkuser, 'email': email, 'phone': phone} ec.update(errors) return render_to_response('joinus.html', ec, context_instance=RequestContext(request)) else: p = Profile(name = ' '.join([vkuser.first_name, vkuser.last_name]), vkontakte_id = vkuser.uid, email = email, phone = phone, photo = vkuser.photo, photo_medium = vkuser.photo_medium, status = u'Игрок') p.save() return redirect('/thankyou/')
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" #make sure user is authenticated user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get user_id via the helper function in utils user_id = utils.getUserId(user) #generate a p_key for this user using the user_id p_key = ndb.Key(Profile, user_id) #get the profile associated with this p_key profile = p_key.get() if not profile: profile = Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() #save profile to datastore return profile # return Profile
def profile_from_user(): """ Return user Profile from datastore, creating new one if non-existent. :return: Profile model for the current endpoint user """ # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException("Authorization required") # get Profile from datastore user_id = get_user_id(user) p_key = ndb.Key(Profile, user_id) profile = p_key.get() # create new Profile if not there if not profile: profile = Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() return profile # return Profile
def post(self, request, *args, **kwargs): request.data.pop('active', None) skills = request.data.pop('skills') now = datetime.utcnow() compensation = request.data.pop('compensation') comp, created = Compensation.objects.get_or_create(**compensation) profile_dict = request.data profile_dict['compensation'] = comp if 'profile_id' not in profile_dict: okStatus = status.HTTP_201_CREATED else: okStatus = status.HTTP_200_OK profile = Profile(**profile_dict) profile.save() # create skills and mapping for skill in skills: skill_data = { 'skill': skill, # 'profile': profile.pk } skill, created = Skill.objects.get_or_create(**skill_data) skill_mapping = { 'profile': profile, 'skill': skill } mapping, created = SkillId.objects.get_or_create(**skill_mapping); z = ProfileSerializer(profile) return Response(z.data, status=okStatus)
def register(request): """Try to register new user""" if request.user.is_authenticated(): return redirect('grunts') if request.method == 'POST': form = CustomRegisterForm(data=request.POST) if not form.is_valid(): return render(request, 'auth/register.html', {'form': form}) else: # If valid form -> create user user = User.objects.create_user( username=form.cleaned_data['username'], password=form.cleaned_data['password1']) # And associate profile profile = Profile() profile.user = user profile.save() # Login registered user user.backend = 'django.contrib.auth.backends.ModelBackend' login_user(request, user) # Go to device list return redirect('grunts') else: form = CustomRegisterForm() return render(request, 'auth/register.html', {'form': form})
def join(request, code): """ TODO: After registring a user invitation should be disable. """ if not check_invitation(code): messages.error(request, 'Your personal URL is incorrect, please ask for new invitation or provide proper url') return redirect('index') from forms import JoinForm if request.method == 'POST': form = JoinForm(request.POST) if form.is_valid(): profile=Profile(first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], unit=form.cleaned_data['unit'], email=form.cleaned_data['email'], key=generate_key()) profile.save() keywords = __to_keywords(form.cleaned_data['keywords']) profile.keywords.clear(); for k in keywords: profile.keywords.add(k) profile.save() return redirect('homepage', code=profile.key ) else: form = JoinForm(initial={'key':code}) return render_to_response('researchers/join.html', { 'form': form, 'key':code, # invitation code },context_instance=RequestContext(request)) return render_to_response('researchers/join.html', {'form':form}, context_instance=RequestContext(request))
def form_valid(self, form): login = form.cleaned_data['login'] password1 = form.cleaned_data['password1'] first_name = form.cleaned_data['first_name'] image = form.cleaned_data['image'] new_user = User( username=login, first_name=first_name, ) new_user.set_password(password1) try: new_user.full_clean() except ValidationError: self.set_message(u'Не правильно заполненна форма', True) return super(CreateCompanyView, self).form_invalid(form) new_user.save() new_profile = Profile( user=new_user, is_company=True, is_report=False, is_super_user=False, image=image, ) new_profile.save() new_company = Company(com_user=new_user) new_company.save() self.set_message(u'Компания успешно добавлена.') return super(CreateCompanyView,self).form_valid(form)
def post_new_user(jwt): try: # Get request data req_data = request.get_json() first_name = req_data.get('first_name') last_name = req_data.get('last_name') location = req_data.get('location', None) description = req_data.get('description', None) contact = req_data.get('contact', None) # Create new Profile instance new_user = Profile( first_name = first_name, last_name = last_name, location = location, description = description, contact = contact ) # Create new entry in database new_user.insert() return jsonify({ 'success':True, 'user': new_user.format() }) except: db.session.rollback() abort(422)
def registration(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = User.objects.create_user(form.cleaned_data['username'], form.cleaned_data['email'], form.cleaned_data['password1']) user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] user.save() profile = Profile(user_id=user.id, phone=form.cleaned_data['phone']) profile.save() messages.info(request, 'Registrácia prebehla úspešne') return HttpResponseRedirect('/') else: form = RegistrationForm() page_info = {} page_info['title'] = 'Registrácia nového uživateľa' page_info['page'] = 1 page_info['form_name'] = 'registration' page_info['form_action'] = '/registracia/' return render_to_response('registracia.html', {'form': form, 'countInfo': countInfo, 'recentNews': recentNews, 'page_info': page_info}, context_instance=RequestContext(request))
def handle_post(self, email, account_info): if self.request.get("profile_entity_key"): profile_key = ndb.Key( urlsafe=self.request.get("profile_entity_key")) profile = profile_key.get() else: profile = Profile(parent=account_info.key, id=email) profile_key = profile.key.urlsafe() if self.get_uploads() and len(self.get_uploads()) == 1: logging.info("Received an image blob with this profile update.") media_blob = self.get_uploads()[0] profile.picture = media_blob.key() else: # There is a chance this is an edit in which case we should check for an existing blob key. original_blob_key = self.request.get("original_blob_key") if original_blob_key: logging.info( "Attaching original blob key (this must have been an edit or duplicate)" ) profile.picture = BlobKey(original_blob_key) profile.name = self.request.get("name") profile.location = self.request.get("location") profile.description = self.request.get("description") profile.dob = datetime.strptime(self.request.get("dob"), "%m/%d/%Y") profile.put() url_redir_str = "./user-profile?profile_entity_key=" + profile_key logging.info(url_redir_str) self.redirect(url_redir_str)
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # TODO 1 # step 1. copy utils.py from additions folder to this folder # and import getUserId from it # step 2. get user id by calling getUserId(user) # step 3. create a new key of kind Profile from the id user_id = utils.getUserId(user) p_key = ndb.Key(Profile, user_id) logging.info("do we even generate a Key?") logging.info(pKey) print >> sys.stderr, "Something to log." # TODO 3 # get the entity from datastore by using get() on the key profile = pKey.get() if not profile: profile = Profile( key = p_key, displayName = user.nickname(), mainEmail= user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) # TODO 2 # save the profile to datastore profile.put() return profile # return Profile
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" # make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # get Profile from datastore user_id = getUserId(user) p_key = ndb.Key(Profile, user_id) # get the entity from datastore by using get() on the key profile = p_key.get() # create a new Profile from logged in user data if not profile: profile = Profile( userId=None, key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) profile.put() return profile
def post(self): form = ProfileForm(data=self.request.POST) if form.is_valid(): user = users.get_current_user() username = self.request.get('username') #profile = Profile.all().filter('user !=', user).filter('username ='******'username ='******'username_exists': ['%s is already exists'] } profile = { 'username': username } template_vars = { 'errors': errors, 'profile': profile } self.render_response('profile/profile_edit.html', template_vars) else: profile = Profile.all().filter('user ='******'/profile') else: template_vars = { 'form': form } self.render_response('profile/profile_edit.html', template_vars)
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" ## TODO 2 ## step 1: make sure user is authed ## uncomment the following lines: # Use endpoints AUTH to get the current user. user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # create a new key of kind Profile from the id p_key = ndb.Key(Profile, user_id) # get the entity from datastore by using get() on the key profile = p_key.get() # profile = None ## step 2: create a new Profile from logged in user data ## you can use user.nickname() to get displayName ## and user.email() to get mainEmail if not profile: profile = Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED), ) # save the profile to the datastore profile.put() return profile # return Profile
def get(self): oauth_token = self.request.get('oauth_token', default_value=None) oauth_verifier = self.request.get('oauth_verifier', default_value=None) user = users.get_current_user() authr = AuthRequest.all().filter('owner = ', user).get() if oauth_token and oauth_verifier and user and authr: host = self.request.headers.get('host', 'nohost') access_token_url = 'https://%s/_ah/OAuthGetAccessToken' % host consumer_key = 'anonymous' consumer_secret = 'anonymous' consumer = oauth.Consumer(consumer_key, consumer_secret) token = oauth.Token(oauth_token, authr.request_secret) token.set_verifier(oauth_verifier) client = oauth.Client(consumer, token) if "localhost" not in host: resp, content = client.request(access_token_url, "POST") if resp['status'] == '200': access_token = dict(cgi.parse_qsl(content)) profile = Profile(owner=user, token=access_token['oauth_token'], secret=access_token['oauth_token_secret']) profile.put() self.redirect("/documentation/credentials")
def register(request): if request.method == 'POST': userform = UserCreationForm(request.POST) proform = ProfileForm(request.POST,request.FILES) # if userform.is_valid(): # new_user = userform.save() # else: # for f in userform: # mylog(str(f)) # if proform.is_valid(): # new_pro = proform.save() # return HttpResponseRedirect("/") if userform.is_valid() and proform.is_valid(): new_user = userform.save() nickname = proform.cleaned_data['nickname'] photo = proform.cleaned_data['photo'] birthday = proform.cleaned_data['birthday'] about = proform.cleaned_data['about'] new_pro = Profile( user=new_user, nickname=nickname, photo=photo, birthday=birthday, about=about ) new_pro.save() return HttpResponseRedirect("/") else: userform = UserCreationForm() proform = ProfileForm() return render_to_response("blog/register.html", {'userform': userform,'proform':proform }, context_instance=RequestContext(request))
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # TODO 1 # step 1. copy utils.py from additions folder to this folder # and import getUserId from it # step 2. get user id by calling getUserId(user) # step 3. create a new key of kind Profile from the id k=getUserId(user) # TODO 3 # get the entity from datastore by using get() on the key p_key=ndb.Key(Profile,k) profile = p_key.get() if not profile: profile = Profile( key = p_key, # TODO 1 step 4. replace with the key from step 3 displayName = user.nickname(), mainEmail= user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) # TODO 2 # save the profile to datastore profile.put() return profile # return Profile
def _get_profile_from_user(self): """Return user Profile from datastore, creating new one if non-existent.""" # Make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') # Try to retrieve an existing profile... user_id = get_user_id(user) key = ndb.Key(Profile, user_id) profile = key.get() # ... and if not exists, create a new Profile from logged in user data if not profile: profile = Profile( userId = user_id, key = key, displayName = user.nickname(), mainEmail= user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) # Create the profile in datastore profile.put() return profile
def register(request): uform = UserForm(request.POST or None) form = PlayerForm(request.POST or None) if uform.is_valid() and form.is_valid(): dj_user = uform.save() player = form.save(commit=False) player.user = dj_user prof = Profile() prof.save() player.profile = prof player.save() #authenticate user #dj_user = authenticate(username=uform.cleaned_data['username'], # password=uform.cleaned_data['password'], # ) #login(request, dj_user) #success sends to map and the questions.. return redirect(reverse('login')) #register invalid.. go back to register (test registration errors!! probably fix css for errors) return render(request, 'registration/register.html', context={ 'form': form, 'uform': uform })
def _getProfileFromUser(self): """Return user Profile from datastore, creating new one if non-existent.""" ## step 1: make sure user is authed user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) # Create an instance of a Key for an id(user email) of a kind(Profile) p_key = ndb.Key(Profile, user_id) # Get the entity(user profile) associated with the key profile = p_key.get() # If the entity does not exist, create a new entity and put in datastore if not profile: profile = Profile( key = p_key, displayName = user.nickname(), mainEmail= user.email(), teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED), ) # put will store profile as a persistent entity in the Datastore profile.put() return profile
def account(request): user = request.user try: profile = Profile.objects.get(user=user) except Exception, e: print e profile = Profile(user=user) profile.save()
def save(self, user): try: data = user.get_profile() except: data = Profile(user=user) data.save()
def save_profile(backend, user, response, *args, **kwargs): try: profile = Profile.objects.get(user=user.pk) except Profile.DoesNotExist: profile = Profile(user=user) profile.save() analist = Analist(user=profile) analist.save()
def register_view(request): """Register a new user.""" if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): data = form.data user = User.objects.create_user(data["username"], data["email"], data["password"]) user.is_active = False user.save() profile = Profile(user=user, show_email=False, show_sign=True, hover_or_click=True, email_for_answer=False) profile.last_ip_address = get_client_ip(request) profile.save() user.backend = "django.contrib.auth.backends.ModelBackend" # Generate a valid token during one hour. uuidToken = str(uuid.uuid4()) date_end = datetime.now() + timedelta( days=0, hours=1, minutes=0, seconds=0) token = TokenRegister(user=user, token=uuidToken, date_end=date_end) token.save() # send email subject = "ZDS - Confirmation d'inscription" from_email = "Zeste de Savoir <{0}>".format(settings.MAIL_NOREPLY) message_html = get_template("email/register/confirm.html").render( Context({ "username": user.username, "url": settings.SITE_URL + token.get_absolute_url() })) message_txt = get_template("email/register/confirm.txt").render( Context({ "username": user.username, "url": settings.SITE_URL + token.get_absolute_url() })) msg = EmailMultiAlternatives(subject, message_txt, from_email, [user.email]) msg.attach_alternative(message_html, "text/html") try: msg.send() except: msg = None return render_template("member/register/success.html", {}) else: return render_template("member/register/index.html", {"form": form}) form = RegisterForm() return render_template("member/register/index.html", {"form": form})
def register(request): #TODO: transaction form = BidderForm(request, request.POST or None) if form.is_valid(): #Generate user user = User.objects.create_user(form.cleaned_data["username"], form.cleaned_data["email"], form.cleaned_data["password1"]) # user.first_name = form.cleaned_data["first_name"] # user.last_name = form.cleaned_data["last_name"] # user.is_active = False user.save() # """ Set cart """ # cart = Cart(bidder=user) # cart.save() """ Set profile """ profile = Profile(user=user) # profile.street_address = form.cleaned_data["street_address"] # profile.city = form.cleaned_data["city"] # profile.state = form.cleaned_data["state"] # profile.zip = form.cleaned_data["zip"] # profile.country = form.cleaned_data["country"] # profile.phone = form.cleaned_data["phone"] # profile.photo = form.cleaned_data["photo"] # profile.birth = datetime.date( # int(form.cleaned_data['year']), # int(form.cleaned_data['month']), # int(form.cleaned_data['day']), # ) profile.save() """ Send mail to confirm account """ email_verify = EmailVerify(user=user, user_activation=True) code = email_verify.generate_code() email_verify.save() #send_mail_account_confirmation(user, email_verify.code, request.shop.name_shop(), request.get_host()) return HttpResponseRedirect(reverse('confirmemail', args=[code])) #return HttpResponseRedirect(reverse('welcome')) print form.errors t = loader.get_template('users/blocks/register.html') c = RequestContext(request, {'form': form}) block_register = (t.render(c)) return HttpResponse( my_render( request, { 'register': block_register, 'page_title': 'Register', 'page_description': 'Register' }, 'register'))
def _save_profile(cd): profile = Profile() profile.id = cd['id'] or None profile.description = cd['description'] profile.name = cd['name'] profile.save() profile.features = cd['features'] profile.save() return profile
def save(self, user_name): data = self.cleaned_data user = get_object_or_404(User, username=user_name) userProfile = Profile( user=user, enroll_number=data['enroll_number'], role='Student', ) userProfile.save()
def create_user_profile(user): try: Profile(username=user.username,email=user.email,password='').save() except: Profile(username=user.username,email='*****@*****.**',password='').save() this_profile = Profile.objects.get(username=user.username) this_profile.save() return this_profile
def index(request, username): # set context dict context_dict = {} # check if profile exists user = User.objects.get(username=username) profile = Profile.objects.filter(user=user) if not profile: profile = False else: profile = profile[0] # upload profile pic if request.method == "POST": if profile: profile(avatar=request.FILES['avatar']) profile.save() else: profile = Profile(user=request.user, avatar=request.FILES['avatar']) profile.save() books = Book.objects.filter(active=True) all_books = Book.objects.all() book_dataset = {} for book in all_books: # create list for smart search on books for quotes section book_dataset[book.title + " - " + book.author] = book.id context_dict['book_dataset'] = json.dumps(book_dataset) for book in books: timedelta = datetime.date.today() - book.start_date if timedelta.days < book.number_of_days: days = Day.objects.filter(book=book) days = sorted(days, key=operator.attrgetter('day'), reverse=False) context_dict['day'] = days[timedelta.days] context_dict['book'] = book context_dict['profile'] = profile # logged in view if request.user.username == username: context_dict['logged_in'] = True context_dict['username'] = request.user.username # public view for users else: context_dict['logged_in'] = False context_dict['username'] = user.username context = RequestContext(request, context_dict) return render(request, 'profiles/index.html', context)
def update(request): id = eval("request." + request.method + "['id']") if Post.objects(id=id): post = Post.objects(id=id)[0] if request.method == 'POST': template = 'admin/index.html' # update field values and save to mongo post.title = request.POST['title'] str_date_published = request.POST['date_published'] post.date_published = datetime.fromtimestamp( mktime(time.strptime(str_date_published, "%b %d %Y"))) post.publisher = request.POST['publisher'] post.papertype = request.POST['papertype'] post.authors = request.POST['authors'] post.additional_info = request.POST['additional_info'] post.page_num = request.POST['page_num'] if request.POST.get('selectedpublication', True): post.selectedpublication = True post.save() params = {'Posts': Post.objects} elif request.method == 'GET': template = 'admin/update.html' params = {'post': post} elif Section.objects(id=id): section = Section.objects(id=id)[0] if request.method == 'POST': template = 'admin/index.html' # update field values and save to mongo section.heading = request.POST['heading'] section.content = request.POST['content'] section.save() params = {'Sections': Section.objects} elif request.method == 'GET': template = 'admin/update.html' params = {'section': section} elif Profile.objects(id=id): profile = Profile.objects(id=id)[0] if request.method == 'POST': template = 'admin/index.html' # update field values and save to mongo profile.details = request.POST['profile'] profile.save() params = {'Profile': Profile.objects.limit(1)} elif request.method == 'GET': template = 'admin/update.html' params = {'Profile': Profile.objects.limit(1)} return render_to_response(template, params, context_instance=RequestContext(request))
def edit_object(self, object_to_edit: Profile, data: dict, current_user: User) -> Profile: if object_to_edit.user.id != current_user.id: raise ForbiddenResourceException( 'Nutzer {0} kann Kaffeeprofil mit der ID {1} nicht bearbeiten.' .format(current_user.public_id, object_to_edit.id)) object_to_edit.name = data['name'] object_to_edit.coffee_strength_in_percent = data[ 'coffee_strength_in_percent'] object_to_edit.water_in_percent = data['water_in_percent'] return object_to_edit
def post(self): user = users.get_current_user() user_name = self.request.get('username') name = self.request.get('name') current_user = Profile(user_name=user_name, name=name, user_id=user.user_id()) current_user.put() dict_variable = {"username": user_name} template = JINJA_ENVIRONMENT.get_template('templates/profile0.html') self.response.write(template.render(dict_variable))
def post(self): profile = users.get_current_user() #Create a new CSSI User in our database cssi_profile = Profile(first_name=self.request.get('first_name'), last_name=self.request.get('last_name'), email=profile.nickname()) cssi_profile.put() self.redirect('/')