def register_view(request): form = UserCreationForm() context = {} if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() profile = Profile(user=user, nickname=form.cleaned_data["nickname"]) profile.save() current_site = get_current_site(request) message = render_to_string( 'users/active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': force_text( urlsafe_base64_encode(force_bytes(user.pk))), 'token': account_activation_token.make_token(user), }) subject = 'Activate your Password Management account.' to_email = form.cleaned_data.get('email') email = EmailMessage(subject, message, to=[to_email]) email.send() messages.add_message( request, messages.INFO, 'Please confirm your email address to complete the registration' ) return HttpResponseRedirect(reverse(settings.LOGIN_REDIRECT_URL)) context['form'] = form return render(request, "users/registration.html", context)
def test_it_lists_profiles_in_slices(): profiles = SQLAlchemyProfiles(db) profiles.add(Profile('11111111', Name('Name 1'))) profiles.add(Profile('11111112', Name('Name 2'))) profiles.add(Profile('11111113', Name('Name 3'))) profiles_list = profiles.list(limit=1) assert len(profiles_list) == 1 assert str(profiles_list[0].name) == 'Name 3' profiles_list = profiles.list(offset=1) assert len(profiles_list) == 2 assert str(profiles_list[0].name) == 'Name 2' assert str(profiles_list[1].name) == 'Name 1' profiles_list = profiles.list(limit=1, offset=1) assert len(profiles_list) == 1 assert str(profiles_list[0].name) == 'Name 2' profiles_list = profiles.list(offset=10) assert len(profiles_list) == 0
def User_Profile_Registration(request): if request.user.is_authenticated(): return HttpResponseRedirect('/') if request.method == 'POST': form = RegistrationForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['profile_pic']) user = User.objects.create_user(username=form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password']) user.first_name = form.cleaned_data['first_name'] user.last_name=form.cleaned_data['last_name'] user.save() profile = Profile(user = user, countries=form.cleaned_data['countries'], about_me = form.cleaned_data['about_me'], birth_date = form.cleaned_data['birth_date']) profile.profile_pic=form.cleaned_data['profile_pic'] profile.save() registredUser = authenticate(username = form.cleaned_data['username'], password= form.cleaned_data['password']) if registredUser is not None: login(request, registredUser) return HttpResponseRedirect('/') else: return HttpResponseRedirect('/registered') else: form = RegistrationForm() context = { 'form' : form } return render_to_response('register.html', context, context_instance=RequestContext(request)) return HttpResponseRedirect('/')
def test_profile_delete(self): u = User(email='*****@*****.**') u.is_active = True u.save() p = Profile(contact_email='*****@*****.**', user=u) p.save() r = Recommendation(profile=p, reviewer_email='*****@*****.**') r.save() self.client.force_login(u) response = self.client.get(reverse('profiles:user_profile_delete')) self.assertEqual(response.status_code, HTTPStatus.OK) User.objects.get(id=u.id) response = self.client.post(reverse('profiles:user_profile_delete'), data={ 'confirm': True, }) self.assertEqual(response.status_code, HTTPStatus.FOUND) self.assertEqual(response.url, reverse('profiles:user')) p = Profile.all_objects.get(id=p.id) self.assertNotEquals(p.deleted_at, None)
def get_profile(user): try: return Profile.all().filter("user = ", user)[0] except IndexError: profile = Profile(user=user, notification=5) profile.save() return profile
def create(self, attrs, instance=None): """ Given a dictionary of deserialized field values, either update an existing model instance, or create a new model instance. """ if instance is not None: instance.user.email = attrs.get('user.email', instance.user.email) instance.poi = attrs.get('poi', instance.poi) instance.user.password = attrs.get('user.password', instance.user.password) return instance print attrs user = attrs.get('user') confirm_password = attrs.get('confirm_password') password = user.get('password') if password != confirm_password: raise serializers.ValidationError('Password confirmation mismatch') check_passwd(password, confirm_password) user = User.objects.create_user(username=user.get('username'), email=user.get('email'), password=user.get('password')) profile = Profile.objects.create(user=user, poi=attrs.get('poi'), email=attrs.get('email')) p = Profile(user=user) print p return Profile(user=user)
def create_profile(user, gender=None, lname=None): if gender is None: gender = get_random_gender() fname = get_random_fname(gender) if lname is None: lname = get_random_lname() zc = get_random_zip() photo = adult_photo(gender) profile = Profile() profile.user = user profile.first_name = fname profile.last_name = lname profile.zip_code = zc profile.gender = gender profile.save() f = open(photo, 'r') np = Photo(album=profile.album, caption="Profile", original_image=File(f)) np.save() profile.set_profile_pic(np) return profile
def handle_label(self, username, **options): from django.contrib.auth.models import User from profiles.models import Profile if '@' in username: kwargs = {'email': username} else: kwargs = {'username': username} try: profile = Profile.objects.get(**kwargs) except Profile.DoesNotExist: try: user = User.objects.get(**kwargs) except User.DoesNotExist: raise CommandError("User '%s' does not exist" % username) print "Adding profile for %s" % username initial = dict([(f.name, getattr(user, f.name)) for f in user._meta.fields]) profile = Profile(user_ptr=user, **initial) profile.save() for f in user._meta.many_to_many: getattr(profile, f.name).add(*getattr(user, f.name).all()) else: raise CommandError("Profile '%s' already exists" % username)
def save_employee_data(request, employee_data, line_count): line_count = line_count + 1 if User.objects.filter(username__iexact=employee_data['email']).exists(): messages.error( request, f"Error! Line: {line_count} {employee_data['email']} email is taken" ) return redirect('upload_employees') elif User.objects.filter(email__iexact=employee_data['email']).exists(): messages.error( request, f"Error! Line: {line_count} {employee_data['email']} email is taken" ) return redirect('upload_employees') else: # Store user detals email = employee_data['email'].lower() user = User.objects.create_user(first_name=employee_data['first_name'], last_name=employee_data['last_name'], username=employee_data['email'], password=employee_data['password'], email=employee_data['email']) user.save() companyObj = None if Company.objects.filter(name=employee_data['company']).exists(): companyObj = Company.objects.get(name=employee_data['company']) else: companyObj = Company(name=employee_data['company']) companyObj.save() profile = Profile(user=user, company=companyObj) profile.save() return
def test_get_profile_response_contains_affiliations( test_client: FlaskClient, yesterday, commit: Callable[[], None]) -> None: address = Address(country=countries.get('gb'), city='City', region='Region') affiliation = Affiliation('1', address=address, organisation='Org', department='Dep', starts=yesterday) profile = Profile('a1b2c3d4', Name('Foo Bar'), '0000-0002-1825-0097') db.session.add(profile) profile.add_affiliation(affiliation) commit() response = test_client.get('/profiles/a1b2c3d4') data = json.loads(response.data.decode('UTF-8')) assert response.status_code == 200 assert response.headers.get( 'Content-Type') == 'application/vnd.elife.profile+json;version=1' assert validate_json(data, schema_name='profile.v1') is True assert len(data['affiliations']) == 1
def post(self, request, *args, **kwargs): form = ProfileForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') username_obj = User.objects.get(username=username) username = username_obj.username raw_password = username_obj.password first_name = username_obj.first_name last_name = username_obj.last_name user = authenticate(username=username, password=raw_password) profile = Profile( user = username_obj, first_name = first_name, last_name=last_name, created_date = timezone.now() ) profile.save() login(request, username_obj) return redirect('/') else: messages.info(request, "Error occured in signup page. ") form = ProfileForm() return render(request, 'blog/signup.html', {'form': form})
def test_delete(self): u = User(email='*****@*****.**') u.is_active = True u.save() p = Profile(contact_email='*****@*****.**', user=u) p.save() r = Recommendation(profile=p, reviewer_email='*****@*****.**') r.save() self.client.force_login(u) response = self.client.get(reverse('profiles:user_delete')) self.assertEqual(response.status_code, HTTPStatus.OK) User.objects.get(id=u.id) response = self.client.post(reverse('profiles:user_delete'), data={ 'confirm': True, }) self.assertEqual(response.status_code, HTTPStatus.FOUND) self.assertEqual(response.url, reverse('profiles:login')) with self.assertRaises(User.DoesNotExist): User.objects.get(id=u.id) with self.assertRaises(Profile.DoesNotExist): Profile.objects.get(id=p.id) Recommendation.objects.get(id=r.id)
def register(request): if request.method == 'POST': form = UserCreationFormExtended(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] email = form.cleaned_data['email'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] new_user = User.objects.create_user(username=username, email=email, first_name=first_name, last_name=last_name, password=password) ## Create a new blank profile here at the ## same time as creating a new user new_Profile = Profile(user=new_user, joined=datetime.now()) new_Profile.save() ##Login new user user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect('/') else: return render(request, 'register/register.html', {'form': form}) else: form = UserCreationFormExtended() return render(request, 'register/register.html', {'form': form})
def test_it_updates_email_addresses(): profile = Profile('12345678', Name('Name')) profile.add_email_address('*****@*****.**', True, True) orcid_record = { 'person': { 'emails': { 'email': [ { 'email': '*****@*****.**', 'primary': True, 'verified': True, 'visibility': 'PUBLIC' }, ] }, } } update_profile_from_orcid_record(profile, orcid_record) assert len(profile.email_addresses) == 1 assert profile.email_addresses[0].email == '*****@*****.**' assert profile.email_addresses[0].restricted is False assert profile.email_addresses[0].position == 0
def create(self, validated_data): user = Profile(**validated_data) user.set_password(validated_data['password']) user.save() # FIXME self.fields.pop('password') return user
def create_credentials(actions): """Creates a login session with permissión for the given actions""" app_a = App(name="Usuarios") app_a.save() created_actions = [] for action in actions: created_actions.append(Action(name=action, label="", app=app_a)) for i in range(0, len(created_actions)): created_actions[i].save() profile = Profile(name='Admin', active=True) profile.save() for action in created_actions: ProfilePermissions(profile=profile, action=action, permission=True).save() password = '******' username = '******' hasher = PBKDF2PasswordHasher() encoded = hasher.encode(password, "Wake Up, Girls!") user1 = User(username=username, password=encoded, name='ADMINISTRADOR', lastname='ADMINISTRADOR', active=True, profile=profile) user1.save() return user1
def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') name = form.cleaned_data.get('name') last_name = form.cleaned_data.get('last_name') email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') # Save user user = authenticate(username=username, password=raw_password) # Save profile user_profile = Profile(user=user, name=name, last_name=last_name, email=email) user_profile.save() login(request, user) return redirect(index) else: form = RegisterForm() return render(request, 'registration/register.html', {'form': form})
def test_profile(self): from profiles.models import Profile p = Profile() self.assertEqual(len(p.my_packages()), 0) r = MockGithubRepo() self.assertEqual(p.url_for_repo(r), None)
def get_profile(user): try: return Profile.all().filter("user = ", user)[0] except IndexError: profile = Profile(user=user, notification=5) profile.save() return profile
def register(request): """ kinda trick because you don't want to call is_valid() on this one :param request: :return: """ if request.POST: form = forms.RegistrationForm(request.POST) if form.is_valid(): print("valid") data = form.cleaned_data if User.objects.filter(email=data['email']).count > 1: print("already used") user = User.objects.create_user( password=form.cleaned_data['password1'], email=form.cleaned_data['email'] ) profile = Profile( user=user, nick=data['nick']) profile.save() authenticated = authenticate(email=data['email'], password=data['password1']) login(request, authenticated) wallet = Wallet(user=request.user) wallet.save() return HttpResponseRedirect(reverse('add-photo')) form = forms.RegistrationForm() return render(request, 'accounts/register.html', { 'form': form })
def form_valid(self, form): self.object = form.save(commit=False) self.object.set_password(form.cleaned_data['password1']) self.object.save() profile = Profile(user=self.object) profile.save() return HttpResponseRedirect(self.get_success_url())
def update(self, instance, attrs): """ Given a dictionary of deserialized field values, either update an existing model instance, or create a new model instance. """ raise serializers.ValidationError('method not valid') print attrs if instance is not None: user = attrs.get('user') print instance.user.email instance.user.email = '*****@*****.**' instance.poi = attrs.get('poi', instance.poi) instance.user.password = attrs.get('user.password', instance.user.password) print instance.user.email instance.save() return instance print attrs user = attrs.get('user') user = User.objects.create_user(username=user.get('username'), email=user.get('email'), password=user.get('password')) profile = Profile.objects.create(user=user, poi=attrs.get('poi')) p = Profile(user=user) print p return Profile(user=user)
def make_profile_for_new_user(sender, user, **kwargs): new_profile = Profile(user=user, id=user.id, confirmed_agreements=True, date_confirmed_agreements=timezone.now()) new_profile.save() assign_perm('change_profile', user, new_profile)
def create_conversation(request): if request.method == 'POST': conversation_json = json.loads(request.body) if 'profile_id' in conversation_json and conversation_json[ 'profile_id']: temporary_profile = get_object_or_404( Profile, pk=conversation_json['profile_id']) else: temporary_profile = Profile( first_name=conversation_json['first_name'], picture_url= "https://www.pngitem.com/pimgs/m/421-4212341_default-avatar-svg-hd-png-download.png" ) temporary_profile.save() inquire = temporary_profile mentor = get_object_or_404(Profile, pk=conversation_json['mentor']) conversation = Conversation(inquire=inquire, mentor=mentor) conversation.save() return JsonResponse( dict(success=True, id=conversation.pk, profile_id=temporary_profile.pk))
def handle(self, *args, **options): for u in User.objects.all(): p = Profile() p.member = u p.save() self.stdout.write('Profiles synced!')
def test_profile(self): from profiles.models import Profile p = Profile() self.assertEqual(len(p.my_packages()), 0) r = MockGithubRepo() self.assertEqual(p.url_for_repo(r), None)
def user_reg(request): username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') name = request.POST.get('student_name') gender = request.POST.get('gender') registerTime = datetime.now() if not (username and email and password): return HttpResponse(json.dumps({"error_code": "Can not be empty!", }), status=400) try: upr = User.objects.get(username=username) #check if there is duplicated username except User.DoesNotExist: upr = None if upr is not None: return HttpResponse(json.dumps({"error": "用户名已被占用", })) try: upr = User.objects.get(email=email) #check if there is duplicated email except User.DoesNotExist: upr = None if upr is not None: return HttpResponse(json.dumps({"error": "Email已被使用", })) try: validate_email(email) except ValidationError: return HttpResponse(json.dumps({"error": "Email格式不正确", })) upr = User.objects.create_user(username, email, password) pr = Profile(user=upr, name=name, gender=gender, registerTime=registerTime) pr.save() return HttpResponse(json.dumps({"id": upr.id, }))
def _update_email_addresses_from_orcid_record(profile: Profile, orcid_record: dict) -> None: orcid_email_dicts = extract_email_addresses(orcid_record) profiles = SQLAlchemyProfiles(db) for index, email_dict in enumerate(orcid_email_dicts): email = email_dict.get('email') try: email_profile = profiles.get_by_email_address(email) except ProfileNotFound: continue if email_profile.id != profile.id: message = ('Profile %s is trying to add email address %s but this ' 'email is associated with profile %s which violates ' 'unique constraint for email addresses' % (profile.id, email, email_profile.id)) LOGGER.error(message) del orcid_email_dicts[index] for email in profile.email_addresses: found = False for orcid_email in orcid_email_dicts: if orcid_email['email'] == email.email: found = True break if not found: profile.remove_email_address(email.email) for orcid_email in orcid_email_dicts: profile.add_email_address( orcid_email['email'], orcid_email['primary'], orcid_email['visibility'] != VISIBILITY_PUBLIC)
def _update_affiliations_from_orcid_record(profile: Profile, orcid_record: dict) -> None: orcid_affiliations = jmespath.search( '"activities-summary".employments."employment-summary"[*]', orcid_record) or [] found_affiliation_ids = set() for index, orcid_affiliation in enumerate(orcid_affiliations): organization = orcid_affiliation['organization'] address = organization['address'] affiliation = Affiliation( affiliation_id=str(orcid_affiliation['put-code']), department=orcid_affiliation.get('department-name'), organisation=organization['name'], address=Address( city=address['city'], region=address.get('region'), country=countries.get(address['country']), ), starts=_convert_orcid_date( orcid_affiliation.get('start-date') or {}), ends=_convert_orcid_date(orcid_affiliation.get('end-date') or {}), restricted=orcid_affiliation['visibility'] != VISIBILITY_PUBLIC, ) profile.add_affiliation(affiliation, index) found_affiliation_ids.add(affiliation.id) for affiliation in profile.affiliations: if affiliation.id not in found_affiliation_ids: profile.remove_affiliation(affiliation.id)
def create_team(request, username): """ Display the TeamCreationForm """ if request.method == 'POST': form = TeamCreationForm(request.POST) if form.is_valid() and request.user.pk == form.cleaned_data['creator']: team = User.objects.create_user(form.cleaned_data['name']) team_creator_attrs = dict( team=team, user=request.user, permission=4, creator=True ) team_creator = TeamMember(**team_creator_attrs) team_creator.save() try: profile = team.get_profile() except Profile.DoesNotExist: profile = Profile(user=team) profile.organization = True profile.creator_id = request.user.pk profile.save() HttpResponseRedirect(reverse('update_team', args=(form.cleaned_data["name"],))) else: form = TeamCreationForm(initial={'creator': request.user.pk}) return render_to_response('teams/team_create.html', {'form': form, 'username': username}, context_instance=RequestContext(request))
def create(self, request): try: first_name = request.data['first_name'] email = request.data['email'] username = request.data['username'] password = request.data['password'] user = User.objects.create_user(username, email, password) user.first_name = first_name user.save() profile = Profile(user=User.objects.get(username=username)) profile.save() serializer_context = {'request': Request(request._request)} return Response(ProfileSerilializer(profile, context=serializer_context).data) except (IntegrityError) as e: if (str(e).find("username") > -1): return Response({"errorMessage" : "Ese usuario ya ha sido tomado"}, 412) else: return Response({"errorMessage" : "Ese correo ya ha sido tomado"}, 412) except (KeyError) as e: return HttpResponse(json.dumps({"errorMessage" : "missing_fields"}), 412) except (User.DoesNotExist): return HttpResponse(json.dumps({"errorMessage" : "Error al crear el ususario"}), 404) except (Exception) as e: return Response({"errorMessage" : "Ese usuario ya ha sido tomado"}, 412)
def save(self): """Create user and profile.""" data = self.cleaned_data data.pop('password_confirmation') user = User.objects.create_user(**data) profile = Profile(user=user) profile.save()
def test_it_normalizes_profile_with_single_email_address( id_, preferred, index, orcid, email): profile = Profile(id_, Name(preferred, index), orcid) profile.add_email_address(email) normalized_profile = normalize(profile) assert len(normalized_profile['emailAddresses']) == 1
def save(self, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email= self.cleaned_data['email'] user.username=user.email profile= Profile(first_name=user.first_name, last_name=user.last_name, is_student=self.cleaned_data["is_student"], email=user.email, username=user.username) profile.save() user.save()
def test_add_user(self): user = AppUser(user=User(email="*****@*****.**"), username="******", email="*****@*****.**", is_staff=True).save() assert not Profile.all().count() profile = get_profile(user) assert profile.notification == 5 assert Profile.all().count()
def normalize_profile(profile: Profile) -> dict: data = normalize_profile_snippet(profile) data['emailAddresses'] = [ normalize(email) for email in profile.get_email_addresses() ] data['affiliations'] = [ normalize(aff) for aff in profile.get_affiliations() ] return data
def test_add_user(self): user = AppUser(user=User(email="*****@*****.**"), username="******", email="*****@*****.**", is_staff=True).save() assert not Profile.all().count() profile = get_profile(user) assert profile.notification == 5 assert Profile.all().count()
def create_default_profile(app, created_models, verbosity, **kwargs): try: user = User.objects.get(id=1) except User.DoesNotExist: user = User(id=1, username="******", email=settings.DEFAULT_FROM_EMAIL) user.save() profile = Profile(user=user, first_name="Notification") profile.save()
def test_it_removes_email_addresses(): profile = Profile('12345678', Name('Name')) profile.add_email_address('*****@*****.**') orcid_record = {'person': {}} update_profile_from_orcid_record(profile, orcid_record) assert len(profile.email_addresses) == 0
def test_it_finds_a_profile_by_email_address_when_exchanging( test_client: FlaskClient) -> None: original_profile = Profile('a1b2c3d4', Name('Foo', 'Bar')) original_profile.add_email_address('*****@*****.**') original_profile.add_email_address('*****@*****.**') db.session.add(original_profile) db.session.commit() with requests_mock.Mocker() as mocker: mocker.post('http://www.example.com/oauth/token', json={ 'access_token': '1/fFAGRNJru1FTz70BzhT3Zg', 'expires_in': 3920, 'foo': 'bar', 'token_type': 'Bearer', 'orcid': '0000-0002-1825-0097', 'name': 'Josiah Carberry' }) mocker.get( 'http://www.example.com/api/v2.1/0000-0002-1825-0097/record', json={ 'person': { 'emails': { 'email': [ { 'email': '*****@*****.**', 'primary': True, 'verified': True, 'visibility': 'PUBLIC' }, { 'email': '*****@*****.**', 'primary': False, 'verified': True, 'visibility': 'PUBLIC' }, ] }, } }) response = test_client.post( '/oauth2/token', data={ 'client_id': 'client_id', 'client_secret': 'client_secret', 'redirect_uri': 'http://www.example.com/client/redirect', 'grant_type': 'authorization_code', 'code': '1234' }) assert Profile.query.count() == 1 assert str(original_profile.name) == 'Josiah Carberry' assert [e.email for e in original_profile.email_addresses ] == ['*****@*****.**', '*****@*****.**'] assert response.status_code == 200
def run(): admin = User.objects.get(pk=1) admin.first_name = u'Главный куратор' admin.save() admin_profile = Profile(user=admin, is_company=False, is_report=True, is_super_user=True, telefon='+7 921 9142583') admin_profile.save()
def list(self, limit: int = None, offset: int = 0, desc: bool = True) -> List[Profile]: query = self.db.session.query(Profile) if desc: query = query.order_by(Profile.desc()) else: query = query.order_by(Profile.asc()) return query.limit(limit).offset(offset).all()
def form_valid(self, form): """Form Valid If form valid User save in database with his profile. Generate Activation key with expire date. For User's email sended confirmation letter Return: Redirect """ form.save() user_email = form.cleaned_data['email'] activation_key = self.generate_activation_key(user_email) key_expires = self.generate_key_expires(settings.KEY_EXPIRE_TERM) user = User.objects.get(email=user_email) user.groups.add(Group.objects.get(name='customers')) slug = self.create_slug(user) new_profile = Profile( user=user, activation_key=activation_key, key_expires=key_expires, slug=slug ) new_profile.save() email_data = { 'username': user.username, 'activation_key': activation_key } email = SendEmailClass( subject=_('Account Confirmation'), sender=settings.EMAIL_HOST_USER, to=settings.EMAIL_SUPERUSERS, template=settings.EMAIL_TEMPLATES['confirmation'], data=email_data ) email.send() return render( self.request, settings.REGISTRATION_TEMPLATES['thanks'], context={ 'username': user.username, 'email': user.email } )
def register(request): ''' Registration for new users and new profiles ''' # if the user is already logged in, send them to their profile if request.user.is_authenticated(): return HttpResponseRedirect('/profile/') # form was submitted if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = User.objects.create_user(username=username,password=password) user.save() age = form.cleaned_data['age'] zipcode = form.cleaned_data['zipcode'] state = form.cleaned_data['state'] gender = form.cleaned_data['gender'] one_k = form.cleaned_data['one_k'] five_k = form.cleaned_data['five_k'] ten_k = form.cleaned_data['ten_k'] one_mile = form.cleaned_data['one_mile'] five_mile = form.cleaned_data['five_mile'] ten_mile = form.cleaned_data['ten_mile'] half_marathon = form.cleaned_data['half_marathon'] full_marathon = form.cleaned_data['full_marathon'] ultra_marathon = form.cleaned_data['ultra_marathon'] trail_run = form.cleaned_data['trail_run'] cross_country = form.cleaned_data['cross_country'] short_distance = form.cleaned_data['short_distance'] long_distance = form.cleaned_data['long_distance'] competitive = form.cleaned_data['competitive'] profile = Profile( user=user, age=age,zipcode=zipcode,state=state, gender=gender,one_k=one_k,five_k=five_k, ten_k=ten_k,one_mile=one_mile,five_mile=five_mile, ten_mile=ten_mile,half_marathon=half_marathon, full_marathon=full_marathon,ultra_marathon=ultra_marathon, trail_run=trail_run,cross_country=cross_country, short_distance=short_distance,long_distance=long_distance, competitive=competitive) profile.save() user = authenticate(username=username,password=password) auth_login(request,user) return HttpResponseRedirect('/profile/') # form was not valid else: context = {'form': form} return render(request,'profiles/register.html', context) # user is not submitting the form else: form = RegistrationForm() context = { 'form': form } return render(request,'profiles/register.html', context)
def get_profile(request): user = request.user if user.is_authenticated(): try: profile = user.get_profile() except Profile.DoesNotExist: profile = Profile(user=user, name=user.username) profile.save() else: profile = "Anonymous" return {"profile": profile}
def create(self, email, password=None, *args, **kwargs): """ Creates and saves a User with the given email, date of birth and password. """ user = self.model(email=email, **kwargs) user.set_password(password) user.save() profile = Profile( user=user, ) profile.save() return user
def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) if commit: user.backend='django.contrib.auth.backends.ModelBackend' user.save() user_profile = Profile() user_profile.user = user user_profile.phone = self.cleaned_data["phone"] user_profile.save() return user
def create_membership(self, team, char_name, active=True): #print(team,char_name) try: return TeamMembership.objects.get(team=team, char_name__iexact=char_name), False except TeamMembership.DoesNotExist: if active: profile, created = Profile(name=char_name, user=self.master_user), True # have to use fake name since admin doesn't have names profile.save() membership = TeamMembership(team=team, profile=profile, char_name=char_name) print("Creating player {0}".format(membership.char_name), file=self.stdout) membership.save() return membership, created return None, False
def register_complete(request, id_booster, key): user = authenticate(username=id_booster, password=key) if not user: raise Http404 if request.method == "POST": form = ProfileCoreForm(request.POST) if form.is_valid(): # User user.first_name = form.cleaned_data["first_name"].lower().title() user.last_name = form.cleaned_data["last_name"].upper() user.set_password(form.cleaned_data["password"]) user.is_active = True user.save() # create corresponding profile profile = Profile() profile.user_id = user.id profile.id_booster = user.username profile.promotion = form.cleaned_data["promotion"] profile.set_last_name(user.last_name) profile.save() # log & redirect user_auth = authenticate(username=user.username, password=form.cleaned_data["password"]) login(request, user_auth) return redirect("accounts-register-rules") else: form = ProfileCoreForm() context = {"form": form, "pending_user": user} return direct_to_template(request, "accounts/register_complete.html", extra_context=context)
def SignUp(request): if request.POST: form = SignUpForm(request.POST) if form.is_valid(): user = form.save() perfil = Profile(usuario=user) perfil.save() return HttpResponseRedirect('/Login/') else: return render_to_response('profiles/signUp.html',{'form':form}, context_instance=RequestContext(request)) if request.user.is_authenticated(): return HttpResponseRedirect('/Now/') else: form = SignUpForm() return render_to_response('profiles/signUp.html',{'form':form}, context_instance=RequestContext(request))
def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) if commit: user.backend='django.contrib.auth.backends.ModelBackend' user.save() user_profile = Profile() user_profile.user = user user_profile.save() department = Department.objects.get(department_Name=self.cleaned_data['department_name']) department.department_Members.add(user) return user
def login_page(request): try: if request.user.is_authenticated: return redirect("profile") data = {} if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") if not email or not password: return render( request, "profiles/login.html", {"error": "Please fill email and password fields"}, ) user = User.objects.get(email=email) user = authenticate(username=user.username, password=password) if user is not None: login(request, user) return redirect("profile") data = { "error": "Invalid credentials, please check your email and password" } except User.DoesNotExist: client.captureException() email = request.POST.get("email") password = request.POST.get("password") username = email.split("@")[0] user = User.objects.create_user( email=email, username=username, password=password ) profile = Profile(user=user) profile.save() user = authenticate(username=username, password=password) login(request, user) return redirect("profile") except Exception as e: client.captureException() logger.error(e) raise Http404 return render(request, "profiles/login.html", data)
def register(request): ''' TO DO: Authenticate email ''' if request.method == 'POST': formUser = UserForm(data=request.POST) formProfile=ProfileForm(data=request.POST) if formUser.is_valid() and formProfile.is_valid(): password1=formUser.cleaned_data['password'] password2=request.POST.get('password2') first_name=formUser.cleaned_data['first_name'] last_name=formUser.cleaned_data['last_name'] email=formUser.cleaned_data['email'] if(password1!=password2): return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile,'passwordError':'passwordError'}) if User.objects.filter(username = email).exists(): return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile, 'error_message':'error_message'}) user = formUser.save() user.set_password(user.password) user.is_active = False user.first_name=first_name user.last_name=last_name user.email=email user.username=email body=formProfile.cleaned_data['body'] birthDate=formProfile.cleaned_data['birthDate'] gender=formProfile.cleaned_data['gender'] city=formProfile.cleaned_data['city'] country=formProfile.cleaned_data['country'] address=formProfile.cleaned_data['address'] postalCode=formProfile.cleaned_data['postalCode'] phoneNumber=formProfile.cleaned_data['phoneNumber'] try: image = request.FILES['image'] except: image="" user.save() newProfile=Profile(user=user,body=body,birthDate=birthDate,gender=gender,city=city,address=address,postalCode=postalCode,phoneNumber=phoneNumber,country=country,image=image) newProfile.save() return HttpResponseRedirect('/profiles/login') else: formUser = UserForm() formProfile=ProfileForm() return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile})
def create_profile(self, user=None, profile_data=None, commit=True): profile = Profile() if user is None: raise NotImplementedError("SignupForm.create_profile requires a valid user") profile.user = user profile.first_name = profile_data["first_name"] profile.last_name = profile_data["last_name"] profile.zip_code = profile_data["zip_code"] profile.gender = profile_data["gender"] profile.source = profile_data["source"] profile.save() return profile
def post(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) profile = Profile(user=user) profile.save() login(request, user) return redirect(request.POST.get('next','/')) context['form'] = form return self.render_to_response(context)
def register(request): u = User() c = PostCount() p = Profile() if request.method == "POST": u.username = request.POST.get('user') u.set_password(request.POST.get('pass')) u.email = request.POST.get('email') u.is_active = True u.is_staff = False u.is_superuser = False u.save() c.user = u c.count = 0 c.save() p.member = u p.save() return HttpResponseRedirect('/login/') return render(request, 'auth/register.html')
def after_signup(self, request, user, emailAddress, **kwargs): profile = None try: profile = Profile.objects.get(user=user) except Profile.DoesNotExist: profile = Profile(user=user) profile.name = self.cleaned_data.get("nickname") #profile.city = City.objects.getById(id=2) #TODO, load from cities cache profile.save() #======================================================= #code in the bookstore '''为注册用户创建购物车''' try: cart = Cart.objects.get(owner=profile) except Cart.DoesNotExist: cart = Cart(owner=profile) cart.save()
def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL): # Now that we've got the magic tokens back from Twitter, we need to exchange # for permanent ones and store them... oauth_token = request.session['request_token']['oauth_token'] oauth_token_secret = request.session['request_token']['oauth_token_secret'] twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET, oauth_token, oauth_token_secret) # Retrieve the tokens we want... authorized_tokens = twitter.get_authorized_tokens(request.GET['oauth_verifier']) # If they already exist, grab them, login and redirect to a page displaying stuff. try: user = User.objects.get(username=authorized_tokens['screen_name']) except User.DoesNotExist: # We mock a creation here; no email, password is just the token, etc. user = User.objects.create_user(authorized_tokens['screen_name'], "*****@*****.**", authorized_tokens['oauth_token_secret']) profile = Profile() profile.user = user profile.oauth_token = authorized_tokens['oauth_token'] profile.oauth_secret = authorized_tokens['oauth_token_secret'] profile.save() user = authenticate( username=authorized_tokens['screen_name'], password=authorized_tokens['oauth_token_secret'] ) login(request, user) redirect_url = request.session.get('next_url', redirect_url) return HttpResponseRedirect("/")
def _register(request): if request.POST: username = request.POST.get('username') email = request.POST.get('email') password = request.POST.get('password') name = request.POST.get('name') gender = 0 if request.POST.get('gender') == "1": gender = 1 elif request.POST.get('gender') == "2": gender = 2 registerTime = datetime.now() else: return HttpResponseRedirect(reverse('index')) try: upr = User.objects.get(username=username) #check if there is duplicated username except User.DoesNotExist: upr = None if upr is not None: return __goErrorPage(request, ["duplicated username", ]) try: upr = User.objects.get(email=email) #check if there is duplicated email except User.DoesNotExist: upr = None if upr is not None: return __goErrorPage(request, ["dupicated email!", ]) form = {} if __judge_form(form): upr = User.objects.create_user(username, email, password) pr = Profile(user=upr, name=name, gender=gender, registerTime=registerTime) pr.save() userpr = authenticate(username=username, password=password) login(request, userpr) else: return __goErrorPage(request, ["something wrong with your form", ]) return HttpResponseRedirect(reverse('index'));
def home(request): user = request.user.username user_exists = Profile.objects.filter(username=user) user_profile = Profile.objects.filter(username=user, completed=False) # Verify if New User if user_exists.count() < 1: profile = Profile(username=user) user_prefs = FilterPreference(username=user) profile.save() user_prefs.save() return HttpResponseRedirect('/swt/profiles/new/') # Verify if Incomplete User Profile elif user_profile.count() > 0: return HttpResponseRedirect('/swt/profiles/new/') else: profile = Profile.objects.get(username=user) args = {} args.update(csrf(request)) args['profile'] = profile # WORKOUTS ARGUMENTS args['workouts'] = Workout.objects.filter(username=user).order_by('-date')[0:5] # FRIENDLIST ARGUMENTS args['friends_accepted'] = FriendList.objects.filter(sender_id=user, accepted=True).order_by('receiver_id') args['friends_pending'] = FriendList.objects.filter(sender_id=user, accepted=False) args['friends_request'] = FriendList.objects.filter(receiver_id=user, accepted=False) args['friends_form'] = FriendsForm() # GYMSTATUS ARGUMENTS args['gym_status'] = GymStatus.objects.all() args['curr_weekday'] = strftime("%A") args['curr_hour'] = strftime("%H") return render_to_response('home-index.html', args)