def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password1'] salt = sha.new(str(random.random())).hexdigest()[:5] activation_key = sha.new(salt+username).hexdigest() key_expires = datetime.datetime.today() + datetime.timedelta(2) user = User.objects.create_user(username, email, password) user.is_active = False user.save() user_profile = UserProfile(user=user, activation_key=activation_key, key_expires=key_expires) user_profile.save() email_subject = "PartyMaker EMail Bestätigung" email_text = "Hallo %s,\n du hast dich bei Party Maker regierstriert. Klicke auf den folgenden\ Link um deinen Account zu aktivieren.\n http://localhost:8000/validate/%s\n mfG das PartyMaker Team" % ( username, activation_key) email_address=settings.REGISTRATION_EMAIL_ADDRESS send_mail(email_subject, email_text, email_address, [email]) return HttpResponseRedirect('thanks') else: form = RegistrationForm() return render_to_response('register.xhtml', {'form':form}, context_instance=RequestContext(request))
def registerUser(request): username = request.POST['username'] password = request.POST['password'] #retyped_password = request.POST['rpassword'] email = request.POST['email'] #check to see that username doesn't already exist if User.objects.filter(username=username).exists(): error = "username already exists" return render(request, 'homepage/registration.html', {"error":error}) # check that passwords match and are >= 5 characters if len(password) < 7: error = "password must be at least 7 characters long" return render(request, 'homepage/registration.html', {"error": error}) else: #create a user and log them in #User Profile Object newUser = UserProfile(username=username, points=0) newUser.save() #django user User.objects.create_user(username, email, password) user = authenticate(username=username, password=password) login(request, user) return redirect('main/')
def subscribe(request,email,lesson_id,token): from django.shortcuts import redirect from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect uname = email.replace('--att--','@') uname = uname.replace('--dot--','.') lesson = Lesson.objects.get(pk=lesson_id) try: user = UserProfile.objects.get(username=uname) except: user = UserProfile() user.username = uname user.set_password('123') user.is_active = True user.email = uname user.save() user.backend = 'main.auth.ProfileUserModelBackend' login(request, user) try: Subscriber2Lesson.objects.get(lesson=lesson, user=user) except: u2l = Subscriber2Lesson() u2l.user = user u2l.lesson = lesson u2l.save() return redirect('my_profile')
class TestSignupView(TestCase): def setUp(self) -> None: self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.user_profile = UserProfile() self.user_profile.user = self.user self.user_profile.save() self.team = Team(name='Kitchen', description='Cook stuff.', max_size=2) self.team.save() self.membership = TeamMembership(team=self.team, member=self.user) self.membership.save() def test_signup_form_validation(self): data = { 'first_name': 'Foo', 'last_name': 'Bar', 'years_on_playa': 2, 'invited_by': 'Baz Qux', 'email': '*****@*****.**', 'password': '******', 'duplicate_password': '******', 'phone': '555-555-5555', 'zipcode': '12345', 'g-recaptcha-response': 'PASSED', 'interested_team': self.team.id, } os.environ['RECAPTCHA_TESTING'] = 'True' form = SignUpForm(data) self.assertTrue(form.is_valid())
def save(self, commit=True): user = super(RegistrationForm, self).save(commit=True) user = UserProfile(user=user, birth_day=self.cleaned_data['birth_day'], phone=self.cleaned_data['phone']) user.save() return user
class TestSignupView(TestCase): def setUp(self) -> None: self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.user_profile = UserProfile() self.user_profile.user = self.user self.user_profile.save() self.team = Team(name='Kitchen', description='Cook stuff.', max_size=2) self.team.save() self.membership = TeamMembership(team=self.team, member=self.user) self.membership.save() def test_signup_form_validation(self): data = { 'first_name': 'Foo', 'last_name': 'Bar', 'years_on_playa': 2, 'invited_by': 'Baz Qux', 'email': '*****@*****.**', 'password': '******', 'duplicate_password': '******', 'phone': '555-555-5555', 'zipcode': '12345', 'g-recaptcha-response': 'PASSED', 'interested_teams': [self.team.id], } os.environ['RECAPTCHA_TESTING'] = 'True' form = SignUpForm(data) self.assertTrue(form.is_valid())
def setUp(self): user = User.objects.create_user(username='******', email='*****@*****.**', password='******') user_profile = UserProfile() user_profile.user = user user_profile.save() self.user_profile = user_profile
def create(self, validated_data): user = User(email=validated_data['email'], username=validated_data['username']) user.set_password(validated_data['password']) user.save() user_profile = UserProfile(user=user) user_profile.save() return user
def create_test_user(name=None): if not name: # pragma: no cover name = ''.join([random.choice(string.ascii_letters) for i in range(10)]) user = User.objects.create_user(name, '*****@*****.**', name) prof = UserProfile(user=user, timezone='America/New_York', email_valid=True, grad_class=2016, membership_status='CAN', location='New York City, NY') prof.save() return user
def run(): User = get_user_model() # Update the users in this list. # Each tuple represents the username, password, email, firstname and lastname of a user. users = [ ('user_1', 'phgzHpXcnJ', '*****@*****.**'), ('user_2', 'ktMmqKcpJw', '*****@*****.**'), ] for username, password, email in users: try: print('Creating user: '******'User ',username, ' successfully created.') except: print('There was a problem creating the user:'******'. Error: ', sys.exc_info()[1]) data_user = [ ['user_1', 'Kees', 'van Kooten'], ['user_2', 'Hoeren', 'Neuken'], ] user_all = User.objects.all() userprofile_all = UserProfile.objects.all() # for i in range(len(data_user)): # does_exist = False # for j in userprofile_all: # if data_user[i][0] == j: # print('data_user_username: '******'userprofile_all: ', j) # does_exist = True for i in range(len(user_all)): print(user_all[i]) does_exist = False for j in userprofile_all: if user_all[i] == j: # print('data_user_username: '******'userprofile_all: ', j) does_exist = True if does_exist == False : for j in range(len(data_user)): if str(user_all[i]) == str(data_user[j][0]): print('OK') p = UserProfile( user = user_all[i], firstname = str(data_user[j][1]), lastname = str(data_user[j][2]), ) p.save()
def save(self, new_user): new_profile = UserProfile(user=new_user, name=self.cleaned_data['name'], city=self.cleaned_data['city'], country=self.cleaned_data['country'], organization=self.cleaned_data['organization'], home_page=self.cleaned_data['home_page'], twitter=self.cleaned_data['twitter']) new_profile.save() return new_profile
def save(self, new_user): new_profile = \ UserProfile(user=new_user, name=self.cleaned_data['name'], city=self.cleaned_data['city'], country=self.cleaned_data['country'], organization=self.cleaned_data['organization'], home_page=self.cleaned_data['home_page'], twitter=self.cleaned_data['twitter']) new_profile.save() return new_profile
def setUp(self) -> None: self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.user_profile = UserProfile() self.user_profile.user = self.user self.user_profile.save() self.team = Team(name='Kitchen', description='Cook stuff') self.team.save()
def join(request): if request.method == 'POST': user = User.objects.create_user(request.POST.get('email'),request.POST.get('email'),request.POST.get('password')) user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.save() user_profile = UserProfile (user=user) user_profile.save() if user is not None: request.session['user'] = user_profile return HttpResponseRedirect(reverse('main.views.dashboard'))
class TestTeamView(TestCase): def setUp(self) -> None: self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.user_profile = UserProfile() self.user_profile.user = self.user self.user_profile.save() self.team = Team(name='Kitchen', description='Cook stuff') self.team.save()
def form_valid(self, form): new_user = form.save(commit=False) new_user.user = new_user new_user.first_name = form.cleaned_data['first_name'] new_user.last_name = form.cleaned_data['last_name'] new_user.is_staff = True new_user.save() new_restaurant = Restaurant(owner=new_user, name=form.cleaned_data['name']) new_restaurant.save() new_profile = UserProfile(user=new_user, owner=new_restaurant) new_profile.save() return super().form_valid(form)
def save_user(self, request, sociallogin, form=None): user = DefaultSocialAccountAdapter.save_user(self, request, sociallogin, form=form) if UserProfile.objects.filter(user=user).exists(): pass else: new_user = UserProfile(user=user, name=user.get_full_name()) new_user.save() # print("Inside the adapter") return redirect('/')
def form_valid(self, form): new_user = form.save(commit=False) new_user.user = new_user new_user.first_name = form.cleaned_data['first_name'] new_user.last_name = form.cleaned_data['last_name'] new_user.save() new_profile = UserProfile(user=new_user, number=form.cleaned_data['number'], city=form.cleaned_data['city'], zip_code=form.cleaned_data['zip_code'], address=form.cleaned_data['address'], allergies=form.cleaned_data['allergies']) new_profile.save() return super().form_valid(form)
def add_user_task(sid, data): try: user = UserProfile.objects.get(login=data['login']) except ObjectDoesNotExist: print('No user') user = UserProfile() user.login = data['login'] user.save() con = UserConnection() con.user = user con.sid = sid con.save() UserConnection.check_online(user)
def register(request): serializer = RegistrationSerializer(data=request.data) if serializer.is_valid(): new_user = User.objects.create( username=serializer.validated_data.get('username'), password=make_password(serializer.validated_data.get('password')), first_name=serializer.validated_data.get('first_name'), last_name=serializer.validated_data.get('last_name'), email=serializer.validated_data.get('email')) new_user_profile = UserProfile(account=new_user) new_user_profile.save() return Response(status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def request_database_add_personal_details(request): constraint = helpers.constraint(request, "POST"); data = constraint.safe({ "first_name": True, "last_name": True, "department": False }); request.user.first_name = data['first_name']; request.user.last_name = data['last_name']; request.user.full_clean(); request.user.clean(); request.user.save(); try: of_department = Department.objects.get(id=data['department']); of_user_profile = UserProfile( user=request.user, department= of_department ); of_user_profile.full_clean(); of_user_profile.clean(); of_user_profile.save(); return redirect("/"); except Department.DoesNotExist: raise Department.DoesNotExist("Index id of department object does not exists"); pass;
def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.username = self.cleaned_data['username'] if commit: user.save() try: profile = user.get_profile() except: profile = UserProfile(user=user) profile.save() return user
def save(self, commit=True): user = User.objects.create_user(self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1']) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] if self.cleaned_data.get('volunteer'): user.groups.add(Group.objects.get(name="Volunteer")) if self.cleaned_data.get('org_admin'): user.groups.add(Group.objects.get(name="Org_Admin")) user.save() profile = UserProfile(user=user) profile.timezone = self.cleaned_data['timezone'] profile.save() return user
def home_profile(request): user = request.user try: profile = user.get_profile() except UserProfile.DoesNotExist: profile = UserProfile(user=user) profile.save() attendships = user.attendships.order_by("date") for attendship in attendships: attendship.past = attendship.date < date.today() return render_to_response('main/home_profile.html', RequestContext(request, {'profile':profile, 'attendships':attendships}))
def handle(self, *args, **options): count = options["users"] users = [] waiters = [] managers = [] _usernames = [] # generate users for i in range(count): n = gen_unique_name(_usernames, ("user_" + "".join(random.sample(string.lowercase, 3)),)) print "generate %d. user (%s)" % (i + 1, n) u = User() u.username = n u.password1 = "".join(random.sample(string.lowercase + string.digits, 10)) u.password2 = u.password1 users.append(u) u.save() # generate user roles # waiters if i % 20 == 1: ur = UserRole() ur.user = u ur.role = _roles[1] ur.restaurant = random.choice(Restaurant.objects.all()) ur.save() print "marking %s as waiter" % u.username waiters.append(u) if u in users: users.remove(u) # managers if i % 40 == 1: ur = UserRole() ur.user = u ur.role = _roles[0] ur.restaurant = random.choice(Restaurant.objects.all()) ur.save() print "marking %s as manager" % u.username managers.append(u) if u in users: users.remove(u) # every 2nd user a profile if i % 2 == 0: print "Adding user profile" profile = UserProfile() profile.user = u profile.save() self.stdout.write('Successfully added %d users' % count)
def createNewUserProfile(user): profile = UserProfile() profile.user = user profile.username = user.username profile.first_name = user.first_name profile.last_name = user.last_name profile.save() return profile
def restore_object(self, attrs, instance=None): def _get_first_last_names(name): name_split = name.split() first_name = name_split[0] last_name = u'' if len(name_split) > 1: last_name = u' '.join(name_split[1:]) return first_name, last_name params = copy.deepcopy(attrs) username = attrs.get('user.username', None) password = attrs.get('user.password', None) name = attrs.get('name', None) email = attrs.get('user.email', None) if username: params['username'] = username if email: params['email'] = email if password: params.update({'password1': password, 'password2': password}) if instance: form = UserProfileForm(params, instance=instance) # form.is_valid affects instance object for partial updates [PATCH] # so only use it for full updates [PUT], i.e shallow copy effect if not self.partial and form.is_valid(): instance = form.save() # get user if email: instance.user.email = form.cleaned_data['email'] if name: first_name, last_name = _get_first_last_names(name) instance.user.first_name = first_name instance.user.last_name = last_name if email or name: instance.user.save() return super(UserProfileSerializer, self).restore_object(attrs, instance) #return instance # TODO: updates form = RegistrationFormUserProfile(params) if form.is_valid(): first_name, last_name = _get_first_last_names(name) new_user = User(username=username, first_name=first_name, last_name=last_name, email=email) new_user.set_password(password) new_user.save() created_by = self.context['request'].user profile = UserProfile(user=new_user, name=attrs.get('name', u''), created_by=created_by, city=attrs.get('city', u''), country=attrs.get('country', u''), organization=attrs.get('organization', u''), home_page=attrs.get('home_page', u''), twitter=attrs.get('twitter', u'')) return profile else: self.errors.update(form.errors) return attrs
def request_temp_log_more_details(request): try: constraint = helpers.constraint(request, "POST"); data = constraint.safe({ "log_id": True, }); of_user = UserProfile.objects.get(user_id=request.user.id); of_log = Log.objects.get( id=data['log_id'], added_by__department_id=of_user.department_id ); return render(request, "ajax_temp/log_details.html", { 'data': of_log, 'out': of_log.out(), "is_out": of_log.is_out_provided(), "LOG" : Log }); except Log.DoesNotExist: raise Log.DoesNotExist("Index id of Log object does not exists"); except UserProfile.DoesNotExist: raise UserProfile.DoesNotExist("Index id of UserProfile object does not exists"); except helpers.InvalidRequest: raise helpers.InvalidRequest("Parameters does not supply required fields") pass; pass;
def setUp(self) -> None: user = User.objects.create_user(username='******', email='*****@*****.**', password='******') user_profile = UserProfile() user_profile.user = user user_profile.save() user2 = User.objects.create_user(username='******', email='*****@*****.**', password='******') user_profile2 = UserProfile() user_profile2.user = user2 user_profile2.save() self.user_profile = user_profile self.user_profile2 = user_profile2
def post(self, request): form = SignUpForm(request.POST) if form.is_valid(): checkuser=User.objects.filter(username=form.cleaned_data.get('username')).first() if checkuser: return redirect('/login/') userdata=dict(form.cleaned_data) profiledata=dict(form.cleaned_data) userdata.pop('phno') userdata.pop('dob') # user = User.objects.create_user(**form.cleaned_data) user = User.objects.create_user(**userdata) profiledata.pop('username') profiledata.pop('password') profiledata.pop('email') obj = User.objects.latest('id') profiledata['user_id']=obj.id profile=UserProfile(dob=profiledata['dob'],phno=profiledata['phno'],user_id=profiledata['user_id']) profile.save() user = authenticate( request, username = form.cleaned_data['username'], password = form.cleaned_data['password'] ) if user is not None: login(request, user) return redirect('/menu_index/') else: messages.error(request, 'Invalid Credentials') return redirect('/login/')
def test_details(self): alice = User.objects.create_user('alice', '*****@*****.**', 'passwd') alice.save() profile = UserProfile(user=alice, biography='Just a small-town girl...', playa_name='Yoshi') profile.save() self.assertEqual(alice.profile, profile) self.assertEqual(set(alice.profile.food_restrictions.all()), set()) vegan = FoodRestriction(name='Vegan', description='No animal products.') vegan.save() alice.profile.food_restrictions.add(vegan) alice.save() self.assertEqual(set(alice.profile.food_restrictions.all()), {vegan})
def createNewUserProfile(user): try: profile = UserProfile.objects.get(user=user) except UserProfile.DoesNotExist: profile = UserProfile() profile.user = user profile.username = user.username profile.first_name = user.first_name profile.last_name = user.last_name profile.save() return profile return None
def enter(request,email,token): from django.shortcuts import redirect from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect uname = email.replace('--att--','@') uname = uname.replace('--dot--','.') try: user = User.objects.get(username=uname) except: user = UserProfile() user.username = uname user.set_password('123') user.is_active = True user.email = uname user.save() user = User.objects.get(username=uname) user.backend = 'main.auth.ProfileUserModelBackend' login(request, user) return redirect('lesson_for_student', id=1)
def Registration(request): if request.user.is_authenticated(): return HttpResponseRedirect('/profile/') if request.method == 'POST': form = UserCreateForm(request.POST) if form.is_valid(): user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password1']) user.save() users = UserProfile(user=user, name=form.cleaned_data['name'], birthday=form.cleaned_data['birthday'], location=form.cleaned_data['location'], bio=form.cleaned_data['bio'], private=form.cleaned_data['private']) users.save() return redirect('LoginRequest') else: return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request)) else: ''' user is not submitting the form, show them a blank registration form ''' form = UserCreateForm() context = {'form': form} return render_to_response('register.html', context, context_instance=RequestContext(request))
def post(request: HttpRequest) -> HttpResponse: if request.method != 'POST': return redirect('signup') if settings.REGISTRATION_CLOSED: return redirect('registration-closed') form = SignUpForm(data=request.POST) if not form.is_valid(): return render(request, 'registration/signup.html', context={ 'form': form, }) with transaction.atomic(): try: User.objects.create_user( username=form.cleaned_data['email'], email=form.cleaned_data['email'], password=form.cleaned_data['password'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name']) except IntegrityError as e: if str(e) == 'UNIQUE constraint failed: auth_user.username': return HttpResponseBadRequest('User already exists.') raise user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password']) assert user is not None user_profile = UserProfile() user_profile.years_on_playa = form.cleaned_data['years_on_playa'] user_profile.invited_by = form.cleaned_data['invited_by'] user_profile.phone_number = form.cleaned_data['phone'] user_profile.zipcode = form.cleaned_data['zipcode'] user_profile.user = user user_profile.save() membership = TeamMembership(member=user, team=form.cleaned_data['interested_team']) membership.save() login(request, user) return redirect(user_profile)
def get_user_avatar(strategy, *args, **kwargs): user = kwargs['user'] backend = kwargs['backend'] response = kwargs['response'] user_profile = None if not UserProfile.objects.filter(user=user).exists(): user_profile = UserProfile(user=user) else: # Already exists, just return. return if isinstance(backend, GoogleOAuth2): if response.get('image') and response['image'].get('url'): url = response['image'].get('url') ext = url.split('.')[-1] user_profile.avatar.save( '{0}.{1}'.format('avatar', ext), ContentFile(urllib2.urlopen(url).read()), save=False ) user_profile.save()
def mainpage(request): #FIX TO REDIRECT context = RequestContext(request) if request.user.is_authenticated(): return HttpResponseRedirect('/main/userpage/') else: if request.method == 'POST': user_form = UserForm(data=request.POST) if user_form.is_valid() and (request.POST['password'] == request.POST['check']): user = user_form.save() user.set_password(user.password) user.save() userprofile = UserProfile() userprofile.user = user.username userprofile.email = user.email userprofile.joined = datetime.datetime.now() userprofile.save() user = authenticate(username=user_form.cleaned_data['username'], password=user_form.cleaned_data['password'], ) login(request, user) return HttpResponseRedirect('/main/userpage/') else: print user_form.errors else: user_form = UserForm() return render_to_response('main/main.html',{'form': user_form,}, context)
def test_saving_and_retrieving_profiles(self): from django.contrib.auth.models import User u1 = User.objects.create(username = '******') u2 = User.objects.create(username = '******') profile1 = UserProfile() profile1.user = u1 profile1.email = '*****@*****.**' profile1.save() profile2 = UserProfile() profile2.user = u2 profile2.email = '*****@*****.**' profile2.save() saved_profiles = UserProfile.objects.all() self.assertEqual(saved_profiles.count(), 2) first_saved_profile = saved_profiles[0] second_saved_profile = saved_profiles[1] self.assertEqual(first_saved_profile.email, '*****@*****.**') self.assertEqual(second_saved_profile.email, '*****@*****.**')
def register(request): if request.method == 'POST': formset = UserForm(request.POST, request.FILES) if formset.is_valid(): newUser = User.objects.create_user(formset.data['username'], formset.data['email'], formset.data['password']) custom = UserProfile(user=newUser) custom.user_id = newUser.id custom.save() newUser = authenticate(username=request.POST['username'], password=request.POST['password']) login(request, newUser) d = {"user": request.user} return render_to_response("registration/register_success.html", d) else: d = {"formset": formset} d.update(csrf(request)) return render_to_response("registration/register.html", d) else: userForm = UserForm() d = {"formset": userForm} d.update(csrf(request)) return render_to_response("registration/register.html", d)
def test_phone_number_parsing(self): alice = User.objects.create_user('alice', '*****@*****.**', 'passwd') alice.save() profile = UserProfile(user=alice, biography='Just a small-town girl...', playa_name='Yoshi') profile.save() test_cases = [ '5555555555', '555-555-5555', '15555555555', '1-555-555-5555', '+15555555555', '+1-555-555-5555', ] for phone_number in test_cases: parsed_number = UserProfile.parse_phone_number(phone_number) assert len(parsed_number) == 12 self.assertTrue(True)
def login_user(request): email = request.POST.get('email') password = request.POST.get('password') user = User.objects.get(email=email) if user.check_password(password): user.backend = 'django.contrib.auth.backends.ModelBackend' login(request,user) userprof = get_user_profile(request) if userprof is None: print "no userprof" if user.first_name: queue = Album(name=user.first_name + "'s Queue") else: queue = Album(name=user.username + "'s Queue") queue.save() userprof = UserProfile(user=user,queue=queue) userprof.save() return HttpResponseRedirect('/') else: return HttpResponseRedirect('/login/')
def setUp(self) -> None: self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.user_profile = UserProfile() self.user_profile.user = self.user self.user_profile.save() self.team = Team(name='Kitchen', description='Cook stuff.', max_size=2) self.team.save() self.membership = TeamMembership(team=self.team, member=self.user) self.membership.save()
def oauth_authenticated(request): token = oauth.Token( request.session['request_token']['oauth_token'], request.session['request_token']['oauth_token_secret'] ) if 'oauth_verifier' in request.GET: token.set_verifier(request.GET['oauth_verifier']) client = oauth.Client(consumer, token) resp, content = client.request(access_token_url, "GET") if resp['status'] != '200': raise Exception("Invalid response from LinkedIn.") access_token = dict(cgi.parse_qsl(content)) headers = {'x-li-format': 'json'} fields = [ 'id', 'first-name', 'last-name', 'email-address', ] url = "http://api.linkedin.com/v1/people/~:(%s)" % ','.join(fields) token = oauth.Token( access_token['oauth_token'], access_token['oauth_token_secret'] ) client = oauth.Client(consumer, token) resp, content = client.request(url, "GET", headers=headers) profile = json.loads(content) # Step 3: lookup the user or create them if they don't exist. firstname = profile['firstName'] lastname = profile['lastName'] identifier = profile['id'] email = profile['emailAddress'] try: user = User.objects.get(username=identifier) except User.DoesNotExist: user = User.objects.create_user( identifier, email, access_token['oauth_token_secret'] ) user.first_name = firstname user.last_name = lastname user.save() # Save our permanent token and secret for later. userprofile = UserProfile() userprofile.user = user userprofile.oauth_token = access_token['oauth_token'] userprofile.oauth_secret = access_token['oauth_token_secret'] userprofile.save() # Authenticate the user and log them in using Django's pre-built # functions for these things. user = authenticate( username=identifier, password=access_token['oauth_token_secret'] ) login(request, user) return HttpResponseRedirect(reverse('home'))
def register(self, request, **cleaned_data): def _get_first_last_names(name): name_split = name.split() first_name = name_split[0] last_name = u'' if len(name_split) > 1: last_name = u' '.join(name_split[1:]) return first_name, last_name new_user = \ super(FHRegistrationView, self).register(request, **cleaned_data) new_profile = \ UserProfile(user=new_user, name=cleaned_data['name'], city=cleaned_data['city'], country=cleaned_data['country'], organization=cleaned_data['organization'], home_page=cleaned_data['home_page'], twitter=cleaned_data['twitter']) new_profile.save() if cleaned_data['name']: fn, ln = _get_first_last_names(cleaned_data['name']) new_user.first_name = fn new_user.last_name = ln new_user.save() return new_user
def database_save_as_out(request): try: constraint = helpers.constraint(request, "POST"); data = constraint.safe({ "log_id": True, "receiver_name": False, "description": False }); of_user = UserProfile.objects.get(user_id=request.user.id); of_log = Log.objects.get( id=data['log_id'], added_by__department_id=of_user.department_id, ); of_out = Out( receiver_name=data['receiver_name'], log=of_log, description=data['description'], added_by=of_user ); of_out.full_clean(); of_out.clean(); of_out.save(); of_log.is_out = True; of_log.save(); return render(request, "ajax_temp/log_details.html", { 'data': of_log, 'out': of_log.out(), "is_out": of_log.is_out_provided(), "LOG" : Log }); except Log.DoesNotExist: raise Log.DoesNotExist("Index id of Log object does not exists"); except UserProfile.DoesNotExist: raise UserProfile.DoesNotExist("Index id of UserProfile object does not exists"); except helpers.InvalidRequest: raise helpers.InvalidRequest("Parameters does not supply required fields") pass;
def post(request: HttpRequest) -> HttpResponse: if request.method != 'POST': return redirect('signup') if settings.REGISTRATION_CLOSED: return redirect('registration-closed') form = SignUpForm(data=request.POST) if not form.is_valid(): return render(request, 'registration/signup.html', context={ 'form': form, }) with transaction.atomic(): try: User.objects.create_user(username=form.cleaned_data['email'], email=form.cleaned_data['email'], password=form.cleaned_data['password'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name']) except IntegrityError as e: if str(e) == 'UNIQUE constraint failed: auth_user.username': return HttpResponseBadRequest('User already exists.') raise user = authenticate(username=form.cleaned_data['email'], password=form.cleaned_data['password']) assert user is not None user_profile = UserProfile() user_profile.years_on_playa = form.cleaned_data['years_on_playa'] user_profile.invited_by = form.cleaned_data['invited_by'] user_profile.phone_number = form.cleaned_data['phone'] user_profile.zipcode = form.cleaned_data['zipcode'] user_profile.user = user user_profile.save() membership = TeamMembership(member=user, team=form.cleaned_data['interested_team']) membership.save() login(request, user) return redirect(user_profile)
def save(self, commit=True): user = User.objects.create_user(self.cleaned_data['username'], self.cleaned_data['email'], self.cleaned_data['password1']) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.groups.add(Group.objects.get(name="Volunteer")) user.save() profile = UserProfile(user=user) profile.timezone = self.cleaned_data['timezone'] profile.grad_class = int(self.cleaned_data['grad_class']) profile.membership_status = self.cleaned_data['member_status'] profile.save() return user
def register_view(request): password = request.POST.get('newpassword') if password != request.POST.get('passcheck'): password = None return HttpResponse('passwords dont match! auth failed!') user = User() user.email = request.POST.get('email') user.username = user.email user.set_password(password) user.first_name = request.POST.get('first') user.last_name = request.POST.get('last') user.save() userProfile = UserProfile() userProfile.user = user userProfile.state = request.POST.get('state') userProfile.city = request.POST.get('city') userProfile.phone = request.POST.get('phone') userProfile.save() return redirect('/')
def populate(): print "Creating Ramya" contact1 = Contacts(addr_line1="18570 NE 58th Ct, #K3084", city="Redmond", state="WA", country="USA", zipcode=98052, email="*****@*****.**") contact1.save() user1 = UserProfile(first_name="Ramya", contact=contact1) user1.save() print "Creating Sanath" contact2 = Contacts(addr_line1="2 Arundel Road, #2", city="Burlingame", state="CA", country="USA", zipcode=94010, email="*****@*****.**") contact2.save() user2 = UserProfile(first_name="Sanath", contact=contact2) user2.save()
def get_tracing_code_info(request): try: constraint = helpers.constraint(request, "POST"); data = constraint.safe({ "tracing_code": True }); of_user_profile = UserProfile.objects.get(id=request.user.id); of_log_details = Log_details.objects.get( tracing_code=data['tracing_code'] ); is_department_log = of_log_details\ .added_by\ .department_id == of_user_profile.department_id; return render(request, "ajax_temp/action_tracking_code_info.html", { 'log_details': of_log_details, 'is_department_log' : is_department_log, "obj_log" : Log, "log_details_person" : of_log_details.person_visitor }); except Log_details.DoesNotExist: raise Log.DoesNotExist("Log details id does not exists"); except UserProfile.DoesNotExist: raise UserProfile.DoesNotExist("Index id of UserProfile object does not exists"); except helpers.InvalidRequest: raise helpers.InvalidRequest("Parameters does not supply required fields") pass; pass;
def run(): User = get_user_model() # Update the users in this list. # Each tuple represents the username, password, email, firstname and lastname of a user. users = [ ('alexanderbouma', '123qweasdzxc', '-'), ('student', '123qweasdzxc', '-'), ('teacher', '123qweasdzxc', '-'), ] for username, password, email in users: try: print('Creating user: '******'User ', username, ' successfully created.') except: print('There was a problem creating the user:'******'. Error: ', sys.exc_info()[1]) data_user = [ ['bramlap', 'Bram', 'Lap'], ['alexanderbouma', 'Alexander', 'Bouma'], ['student', 'Student', 'Student'], ['teacher', 'Teacher', 'Teacher'], ] user_all = User.objects.all() userprofile_all = UserProfile.objects.all() for i in range(len(user_all)): does_exist = False for j in userprofile_all: if user_all[i] == j: does_exist = True if does_exist == False: for j in range(len(data_user)): if str(user_all[i]) == str(data_user[j][0]): if str(user_all[i]) == 'teacher': p = UserProfile( user=user_all[i], firstname=str(data_user[j][1]), lastname=str(data_user[j][2]), is_student=False, is_teacher=True, ) p.save() else: p = UserProfile( user=user_all[i], firstname=str(data_user[j][1]), lastname=str(data_user[j][2]), ) p.save() print('OK')
def create_profile(sender, **kw): user = kw["instance"] if kw["created"]: user_profile = UserProfile() user_profile.user = user user_profile.save()
def clean_phone(self) -> str: return UserProfile.parse_phone_number(self.cleaned_data['phone'])
def register(request): if request.method == 'GET': return JsonResponse({ 'status': 3, 'message': 'The API where new users can register themselves on the app.' }) if request.method == 'POST': try: # just to decode JSON properly data = json.loads(request.body.decode('utf8').replace("'", '"')) except: return JsonResponse({ "message": "Please check syntax of JSON data passed.", 'status': 4 }) try: # see whether all fields passed in JSON or not data['name'] data['email'] data['phone'] data['emergency_phone'] except KeyError as missing_data: return JsonResponse({ "message": "Missing the following field: {}".format(missing_data), 'status': 2 }) try: int(data['phone']) except: #phone numbers should be an integer or string only of numbers return JsonResponse({ 'status': 0, 'message': 'Please enter a valid Phone Number.' }) try: int(data['emergency_phone']) except: #phone numbers should be an integer or string only of numbers return JsonResponse({ 'status': 0, 'message': 'Please enter a valid Emergency Phone Number.' }) if len(data['phone']) != 10: return JsonResponse({ 'status': 0, 'message': 'Please enter a valid Phone Number.' }) if len(data['emergency_phone']) != 10: return JsonResponse({ 'status': 0, 'message': 'Please enter a valid Emergency Phone Number.' }) email = data['email'] if not re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", email): return JsonResponse({ 'status': 0, 'message': 'Please enter a valid Email address.' }) try: UserProfile.objects.get(email=email) return JsonResponse({ 'status': 0, 'message': 'This Email has already been registered. Try some other email.' }) except: pass try: profile = UserProfile() name = ' '.join(str(data['name']).strip().split()) profile.name = name profile.email = str(data['email']) profile.phone = int(data['phone']) profile.emergency_phone = int(data['emergency_phone']) profile.save() #verify email send_to = profile.email body = email_body.register() email_token = utils.generate_email_token(profile) body = body % ( name, str(request.build_absolute_uri(reverse("main:nill"))) + 'email_confirm/' + email_token + '/') sg = sendgrid.SendGridAPIClient(apikey=SENDGRID_API_KEY) from_email = Email('*****@*****.**') to_email = Email(send_to) subject = "Email Confirmation for your account on Alertify app" content = Content('text/html', body) try: mail = Mail(from_email, subject, to_email, content) response = sg.client.mail.send.post(request_body=mail.get()) except Exception: profile.delete() return JsonResponse({ 'message': 'Error sending email. Please try again.', 'status': 0 }) message = "Registration successful! A confirmation link has been sent to %s. Kindly click on it to verify your email address." % ( send_to) return JsonResponse({'message': message, 'status': 1}) except Exception: return JsonResponse({ 'message': 'Registration failed due to unknown reasons.', 'status': 0 })