def create(self, validated_data): user_dict = validated_data['user'] tag_dict = validated_data['tag'] first_in_required = [ f for f in self._required if f in user_dict ][0] user = { 'id': lambda: UserProfile.objects.get(user__id=user_dict['id']), 'student_id': lambda: UserProfile.get_by_student_id(user_dict['student_id']), 'username': lambda: UserProfile.objects.get(user__username=user_dict['username']), 'email': lambda: UserProfile.get_by_email(user_dict['email']), }[first_in_required]() tag = UserTag.objects.get( slug=tag_dict['slug'], course_instance=self.context['course_id'] ) obj, created = UserTagging.objects.set(user, tag) if not created: raise serializers.ValidationError( 'User {user} already has tag {slug}'.format( user=user.user.username, slug=tag.slug, ) ) return obj
def unblockFriend(request): response = dict() userid = request.REQUEST['userid'] friendid = request.REQUEST['friendid'] try: userProfile = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse("Invalid user id") try: friendProfile = UserProfile.getUser(friendid) except UserProfile.DoesNotExist: return errorResponse("Invalid friend id") if friendProfile not in userProfile.friends.all(): return errorResponse("Target is not your friend") if friendProfile in userProfile.blockedFriends.all(): userProfile.blockedFriends.remove(friendProfile) userProfile.save() response['success'] = True return HttpResponse(json.dumps(response))
def create(self, validated_data): user_dict = validated_data['user'] tag_dict = validated_data['tag'] first_in_required = [f for f in self._required if f in user_dict][0] user = { 'id': lambda: UserProfile.objects.get(user__id=user_dict['id']), 'student_id': lambda: UserProfile.get_by_student_id(user_dict['student_id']), 'username': lambda: UserProfile.objects.get(user__username=user_dict['username' ]), 'email': lambda: UserProfile.get_by_email(user_dict['email']), }[first_in_required]() tag = UserTag.objects.get(slug=tag_dict['slug'], course_instance=self.context['course_id']) obj, created = UserTagging.objects.set(user, tag) if not created: raise serializers.ValidationError( 'User {user} already has tag {slug}'.format( user=user.user.username, slug=tag.slug, )) return obj
def save(self, commit=True): if not commit: raise NotImplementedError("Can't create User and UserProfile without database save") user = super(UserCreateForm, self).save(commit=True) user_profile = UserProfile(user=user, first_name=self.cleaned_data['first_name'], second_name = self.cleaned_data['second_name'], status=True, latitude = self.cleaned_data['latitude'], longitude = self.cleaned_data['longitude'], timestamp=datetime.datetime.now()) user_profile.save() return user, user_profile
def edit_profile(request): context = RequestContext(request) try: user_profile = UserProfile.objects.get(user=request.user) except UserProfile.DoesNotExist: user_profile = UserProfile(user=request.user) if request.method == 'POST': edit_form = ProfileForm(request.POST) if edit_form.is_valid(): data = edit_form.cleaned_data user_profile.full_name = data['full_name'] user_profile.bio = data['bio'] user_profile.save() return HttpResponseRedirect( reverse('userprofile.views.profile', args=(), kwargs={'username': request.user.username})) else: print edit_form.errors else: edit_form = ProfileForm({ 'full_name': user_profile.full_name, 'bio': user_profile.bio }) context_dict = { 'edit_form': edit_form } return render_to_response('userprofile/edit.html', context_dict, context)
def save(self, profile_callback = None): """ Create the new ``User`` and ``RegistrationProfile``, and returns the ``User``. This is essentially a light wrapper around ``RegistrationProfile.objects.create_inactive_user()``, feeding it the form data and a profile callback (see the documentation on ``create_inactive_user()`` for details) if supplied. """ new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'], sex=self.cleaned_data['sex'], age=self.cleaned_data['age'], origin=self.cleaned_data['origin'], ethnicity=self.cleaned_data['ethnicity'], disadvantaged=self.cleaned_data['disadvantaged'], employment_location=self.cleaned_data['employment_location'], position=self.cleaned_data['position'], password=self.cleaned_data['password1'], email=self.cleaned_data['email'], profile_callback=profile_callback) # Extending the user model with UserProfile new_profile = UserProfile(user = new_user, sex=self.cleaned_data['sex'], age=self.cleaned_data['age'], origin=self.cleaned_data['origin'], ethnicity=self.cleaned_data['ethnicity'], disadvantaged=self.cleaned_data['disadvantaged'], employment_location=self.cleaned_data['employment_location'], position=self.cleaned_data['position']) new_profile.save() return new_user
def make_user(**kwargs): newUser = User(**kwargs) newUser.set_password(kwargs['password']) newUser.save() newProfile = UserProfile(user=newUser) newProfile.save() return newUser
def register(request): if request.method=="GET": return render(request, "register.html") else: form=AricleForm(request.POST) if form.is_valid(): # reg=form.save(commit=False) # reg.save() pk=auth() u=request.POST['username'] pw=request.POST['password'] email=request.POST['email'] user=User.objects.create_user(u,email,pw) user.is_active=False user.save() userprofile=UserProfile(user=user) userprofile.save() # user=User.objects.get(username=user) active=Active(user=user,auth=pk) active.save() # print('request.get_host()',request.get_host()) text="http://%s/register/active/%s" %(request.get_host() ,pk) #text = "http://127.0.0.1/register/active/%s" % pk print("text",text) #sendemail(text,email) return HttpResponse(text) else: return render(request, "register.html", {"form": form})
def savetrainers(): with open("sisteme_eklenecek_egitmenler.csv") as e: egitmenler = e.readlines() for egit in egitmenler: print egit cols = egit.split('|') try: egitu = User(first_name=cols[0], last_name=cols[1], email=cols[4].rstrip(), username=cols[4].rstrip()) egitu.set_password = '******' egitu.save() egitup = UserProfile(user=egitu, organization=cols[2], tckimlikno='', ykimlikno='', gender='', mobilephonenumber='', address='', job='', city='', title='', university='', department='', country=cols[3], is_instructor=True) egitup.save() print "olustu" print cols[4].rstrip() except: print "olusmadi" print cols[4].rstrip()
def poke(request): response = dict() userid = request.REQUEST['userid'] friendid = request.REQUEST['friendid'] lastHour = datetime.utcnow().replace(tzinfo=pytz.utc) - timedelta(hours=1) try: user = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse("Invalid user id") try: targetUser = UserProfile.getUser(friendid) except UserProfile.DoesNotExist: return errorResponse("Invalid target user id") if targetUser not in user.friends.all(): return errorResponse("User is not your friend") poke = Poke.objects.filter(sender=user, recipient=targetUser, created__gt=lastHour) if poke: return errorResponse("Already poked user in the last hour") poke = Poke.objects.create(sender=user, recipient=targetUser) # sendPokeNotification(poke) response['success'] = True return HttpResponse(json.dumps(response))
def savetrainers(): with open("sisteme_eklenecek_egitmenler.csv") as e: egitmenler = e.readlines() for egit in egitmenler: print egit cols=egit.split('|') try: egitu = User(first_name=cols[0],last_name=cols[1],email=cols[4].rstrip(),username=cols[4].rstrip()) egitu.set_password = '******' egitu.save() egitup = UserProfile(user=egitu, organization=cols[2], tckimlikno='', ykimlikno='', gender='', mobilephonenumber='', address='', job='', city='', title='', university='', department='', country=cols[3], is_instructor=True) egitup.save() print "olustu" print cols[4].rstrip() except: print "olusmadi" print cols[4].rstrip()
def user_registration(request): if request.user.is_authenticated(): return redirect('/') form = RegisterForm(request.POST or None) if form.is_valid(): user = form.save() user.set_password(user.password) user.save() profile = UserProfile() profile.user = user profile.save() send_mail( 'Welcome to ' + DOMAIN + '!', 'Someone try register on site ' + DOMAIN + '. To confirm registration visit this link ' + confirmation_link + '. If you aren\'t try to register than just ignore this email. ''', '*****@*****.**', ['*****@*****.**'], fail_silently=False) return redirect('/') context = RequestContext(request) return render_to_response('userprofile/registration.html', {'form': form}, context)
def test_userprofile_get_by_student_id(self): self.assertEqual(self.student_profile, UserProfile.get_by_student_id("12345X")) self.assertEqual(self.grader_profile, UserProfile.get_by_student_id("67890Y")) self.assertRaises(UserProfile.DoesNotExist, UserProfile.get_by_student_id, "111111")
def inviteToStatus(request): response = dict() userid = request.REQUEST['userid'] statusId = request.REQUEST['statusid'] friends = request.REQUEST.get('friends', '[]') friends = json.loads(friends) try: userProfile = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse('Invalid User') try: status = Status.getStatus(statusId) except Status.DoesNotExist: return errorResponse('Invalid Status') # if status.user != userProfile: # if status.visibility == Status.VIS_FRIENDS or status.visibility == Status.VIS_CUSTOM: # return errorResponse("Cant invite people to private events") buddyupFriends = list() facebookFriends = list() for friendId in friends: friendId = str(friendId) if friendId[:2] == 'fb': friendId = friendId[2:] try: friend = UserProfile.objects.get(facebookUID=friendId) if friend != status.user and friend not in status.attending.all(): buddyupFriends.append(friend) except UserProfile.DoesNotExist: try: fbFriend = FacebookUser.objects.get(facebookUID=friendId) except FacebookUser.DoesNotExist: fbFriend = FacebookUser.objects.create(facebookUID=friendId) facebookFriends.append(fbFriend) else: try: friend = UserProfile.getUser(friendId) if friend != status.user and friend not in status.attending.all(): buddyupFriends.append(friend) except UserProfile.DoesNotExist: pass status.invited.add(*buddyupFriends) status.fbInvited.add(*facebookFriends) createInvitedToStatusNotification(buddyupFriends, userProfile, status) sendInvitedToStatusNotification(status, userProfile, buddyupFriends) response['success'] = True return HttpResponse(json.dumps(response))
class SubmissionCreateAndReviewForm(SubmissionReviewForm): STUDENT_FIELDS = ('students', 'students_by_user_id', 'students_by_student_id', 'students_by_email') submission_time = forms.DateTimeField() students = forms.ModelMultipleChoiceField( queryset=UserProfile.objects.none(), required=False) students_by_user_id = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda user_id: User.objects.get(id=user_id).userprofile, choices=[], required=False) students_by_student_id = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda student_id: UserProfile.get_by_student_id(student_id), choices=[], required=False) students_by_email = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda email: UserProfile.get_by_email(email), choices=[], required=False) def __init__(self, *args, **kwargs): super(SubmissionCreateAndReviewForm, self).__init__(*args, **kwargs) self.fields["students"].queryset = \ UserProfile.objects.all() self.fields["students_by_user_id"].choices = \ [ (p.user_id, p) for p in UserProfile.objects.all() ] self.fields["students_by_student_id"].choices = \ [ (p.student_id, p.student_id) for p in UserProfile.objects.all() ] self.fields["students_by_email"].choices = \ [ (u.email, u.email) for u in User.objects.all() ] def clean(self): self.cleaned_data = data = super(SubmissionCreateAndReviewForm, self).clean() fields = self.STUDENT_FIELDS n = sum((1 if data.get(k) else 0) for k in fields) if n == 0: raise forms.ValidationError( _("One of the student fields must not be blank")) if n > 1: raise forms.ValidationError( _("Only one student field can be given")) return data @property def cleaned_students(self): data = self.cleaned_data for field in self.STUDENT_FIELDS: s = data.get(field) if s: return s raise RuntimeError("Didn't find any students")
def setGroupMembers(request): response = dict() userid = request.REQUEST['userid'] groupid = request.REQUEST['groupid'] friendids = request.REQUEST.get('friendids', []) friendids = json.loads(friendids) try: userProfile = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse("Invalid user id") try: group = Group.objects.get(pk=groupid) except Group.DoesNotExist: return errorResponse("Invalid group id") if group.user != userProfile: return errorResponse("User does not own that group") userFriends = userProfile.friends.all() group.members.clear() group.fbMembers.clear() for friendid in friendids: friendid = str(friendid) if friendid[:2] == 'fb': friendid = friendid[2:] if friendid: try: friendProfile = UserProfile.objects.get(facebookUID=friendid) group.members.add(friendProfile) except UserProfile.DoesNotExist: try: facebookUser = FacebookUser.objects.get(facebookUID=friendid) except FacebookUser.DoesNotExist: facebookUser = FacebookUser.objects.create(facebookUID=friendid) group.fbMembers.add(facebookUser) else: try: friend = UserProfile.getUser(friendid) except User.DoesNotExist: return errorResponse("Friend does not exist") if friend not in userFriends: return errorResponse("User is not a friend") group.members.add(friend) group.save() response['success'] = True return HttpResponse(json.dumps(response))
def createTestUser(request): numberOfFriends = request.REQUEST['numfriends'] response = dict() name = "test%d" % random.randint(1, 10000000) email = "*****@*****.**" % name firstName = name lastName = name user = User(username=email, email=email, first_name=firstName, last_name=lastName, password=0) user.save() userProfile = UserProfile(user=user, device='ios') userProfile.save() numberOfFriends = int(numberOfFriends) friends = UserProfile.objects.all().order_by('-id')[:numberOfFriends] blockedFriends = userProfile.blockedFriends.all() for friend in friends: if friend not in friend.friends.all(): friend.friends.add(userProfile) userProfile.friends.add(friend) friends = userProfile.friends.all() response['friends'] = list() for friend in friends: friendData = getUserProfileDetailsJson(friend) response['friends'].append(friendData) statusesResponse, newSince = getNewStatusesJsonResponse(userProfile, None, None, None) myStatusesResponse = getMyStatusesJsonResponse(userProfile) groupsData = getMyGroupsJsonResponse(userProfile) buddyupSettings = getSettingsData(userProfile) newSince = datetime.now().strftime(MICROSECOND_DATETIME_FORMAT) notifications = getNotificationsJson(userProfile) chatData = getNewChatsData(userProfile) response['success'] = True response['firstname'] = userProfile.user.first_name response['lastname'] = userProfile.user.last_name response['userid'] = userProfile.id response['facebookid'] = userProfile.facebookUID response['statuses'] = statusesResponse response['groups'] = groupsData response['mystatuses'] = myStatusesResponse response['chats'] = chatData response['newsince'] = newSince response['settings'] = buddyupSettings response['notifications'] = notifications response['favoritesnotifications'] = userProfile.favoritesNotifications return HttpResponse(json.dumps(response))
def register(request): if request.method == 'POST': form = NewUserForm(request.POST) if form.is_valid(): new_user = form.save() userprofile = UserProfile(user=new_user, steamURL=form.cleaned_data["steamURL"]) userprofile.save() return HttpResponseRedirect("/inventory") else: form = NewUserForm() return render(request, "registration/register.html", { 'form': form, })
def save(self, commit=True): if not commit: raise NotImplementedError("Can't create User and UserProfile without database save") user = super(UserCreateForm, self).save(commit=True) user_profile = UserProfile( user = user, latitude = self.cleaned_data['latitude'], longitude = self.cleaned_data['longitude'], points = 0, rank_points = 0, avatar = self.cleaned_data['avatar']) user_profile.save() return user, user_profile
def _update_user_profile(self, user_profile: UserProfile, profile_data: Dict): """ Update user profile from validated data. """ profile_updated = False for key, new_val in profile_data.items(): current_val = getattr(user_profile, key) if new_val != current_val: setattr(user_profile, key, new_val) profile_updated = True if profile_updated: user_profile.save()
def createInst(self,postrequest,numofinst): insts=[] uprof=UserProfileOPS() for i in xrange(numofinst): n_str=str(i)+'-' upass=uprof.generatenewpass() # uretilen parola olusturulan kullaniciya gonderilecek. inst=User(first_name=postrequest[n_str+'first_name'],last_name=postrequest[n_str+'last_name'], email=postrequest[n_str+'email'],username=postrequest[n_str+'email'],password=upass) inst.save() instprof=UserProfile(job=postrequest[n_str+'job'],title=postrequest[n_str+'title'], organization=postrequest[n_str+'organization'],is_instructor=True, user=inst) instprof.save() insts.append(instprof) return insts
def post(self, request, *args, **kwargs): form = RegistrationForm(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['password'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name']) user.save() userprofile = UserProfile(user=user, organizacion=request.user.get_profile().organizacion) userprofile.save() return HttpResponseRedirect('/accounts/register_success/') else: return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
def test_submit_success(self): uprofile = UserProfile(user=self.user, token='randomtoken') uprofile.save() response = self.client.get( reverse('collector:bookmark', args=(self.user.username,)) + "?" + "&".join( key + '=' + value for key, value in { 'url': 'http://www.moto-net.com/rss_actu.xml', 'from': 'me', 'source': 'all', 'token': 'randomtoken', }.items() )) self.assertEqual(response.status_code, 202)
def test_facebook_first_visit(self): profiles = UserProfile.all().fetch(100) self.assertEquals(len(profiles), 0) fb_profiles = FacebookProfile.all().fetch(100) self.assertEquals(len(fb_profiles), 0) users = DatastoreUser.all().fetch(100) self.assertEquals(len(users), 0) _facebook_login(self) fb_profiles = FacebookProfile.all().fetch(100) self.assertEquals(len(fb_profiles), 1) profiles = UserProfile.all().fetch(100) self.assertEquals(len(profiles), 1) users = DatastoreUser.all().fetch(100) self.assertEquals(len(users), 1)
def save(request): userprofile = UserProfile.get_for_user(request.user) if not userprofile: raise PermissionDenied if request.POST: form = SavedSearchForm(request.POST) if form.is_valid(): saved_search = form.save(commit=False) saved_search.slug = unique_slug(form.cleaned_data['name']) saved_search.owner = userprofile saved_search.save() form.save_m2m() return HttpResponseRedirect(reverse('browse-offers')) else: initial = {} if request.GET.get('donor'): initial['donor'] = get_object_or_404(UserProfile, user__username=request.GET['donor']) if request.GET.get('max_distance'): initial['max_distance'] = request.GET['max_distance'] if request.GET.get('watched_users'): initial['watched_users'] = request.GET['watched_users'] try: longitude, latitude = (float(request.GET['longitude']), float(request.GET['latitude'])) initial['location'] = Point(longitude, latitude) except (KeyError, TypeError, ValueError): pass form = SavedSearchForm(initial=initial) return render_to_response_context(request, "saved/save_search.html", {'form': form});
def deleteStatus(request): response = dict() userid = request.REQUEST['userid'] statusid = request.REQUEST['statusid'] try: userProfile = UserProfile.getUser(userid) cacheKey = Status.getCacheKey(statusid) status = cache.get(cacheKey) if status is None: status = Status.getStatus(statusid) except UserProfile.DoesNotExist: return errorResponse("Invalid user id") except Status.DoesNotExist: return errorResponse("Invalid statusid") if status.user == userProfile: status.deleted = True status.save() response['success'] = True createDeleteStatusNotification(status) sendDeleteStatusNotfication(status) else: response['success'] = False response['error'] = "Can not delete another user's status" return HttpResponse(json.dumps(response))
def create_profile_handler(sender, **kwargs): user_instance = kwargs['instance'] if user_instance.is_staff == True: try: user_instance.get_profile() except: UserProfile(user = user_instance).save()
def sendStatusMessage(request): response = dict() text = request.REQUEST['text'] userid = request.REQUEST['userid'] statusid = request.REQUEST['statusid'] lastMessageId = request.REQUEST.get('lastmessageid', None) try: userProfile = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse('Invalid User') try: status = Status.getStatus(statusid) except Status.DoesNotExist: return errorResponse('Invalid status id') message = StatusMessage.objects.create(user=userProfile, text=text, status=status) sendStatusMessageNotification(message) createCreateStatusMessageNotification(message) response['success'] = True response['messages'] = getNewStatusMessages(status, lastMessageId) return HttpResponse(json.dumps(response))
def suggestLocationTime(request): response = dict() userid = request.REQUEST['userid'] statusid = request.REQUEST['statusid'] suggestionType = request.REQUEST['type'] location = request.REQUEST.get('location', None) time = request.REQUEST.get('time', None) if suggestionType != 'location' or suggestionType != 'time': return errorResponse('type must be location or time') try: userProfile = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse('Invalid User') try: cacheKey = Status.getCacheKey(statusid) status = Status.getStatus(statusid) except Status.DoesNotExist: return errorResponse('Invalid status id') if suggestionType == 'location': location = getLocationObjectFromJson(json.loads(location)) locationSuggestion = LocationSuggestion.objects.get_or_create(user=userProfile, status=status, location=location) if suggestionType == 'time': date = datetime.strptime(time, DATETIME_FORMAT) timeSuggestion = TimeSuggestion.objects.get_or_create(user=userProfile, status=status, dateSuggested=time) response['success'] = True return HttpResponse(json.dumps(response))
def get_queryset(self, request): if not request.user.is_superuser: profile = UserProfile.get_by_request(request) return self.model.objects.where_staff_includes(profile) else: return self.model.objects.all()
def cancelStatus(request): response = dict() userid = request.REQUEST['userid'] statusid = request.REQUEST['statusid'] try: userProfile = UserProfile.getUser(userid) cacheKey = Status.getCacheKey(statusid) status = cache.get(cacheKey) if status is None: status = Status.getStatus(statusid) except UserProfile.DoesNotExist: return errorResponse("Invalid user id") except Status.DoesNotExist: return errorResponse("Invalid statusid") if status.user != userProfile: return errorResponse("User does not own this status") now = datetime.utcnow() if status.expires > now: status.expires = now status.save() response['success'] = True return HttpResponse(json.dumps(response))
def get_queryset(self, request): if not request.user.is_superuser: profile = UserProfile.get_by_request(request) return profile.teaching_courses else: return self.model.objects.filter()
def createStatusJsonObject(status, userProfile = None): statusData = dict() statusData['statusid'] = status.id statusData['userid'] = status.user_id statusData['userinfo'] = getUserProfileDetailsJson(status.user) statusData['text'] = status.text statusData['datecreated'] = status.dateCreated.strftime(DATETIME_FORMAT) statusData['dateexpires'] = status.expires.strftime(DATETIME_FORMAT) statusData['datestarts'] = status.starts.strftime(DATETIME_FORMAT) statusData['type'] = status.statusType statusData['deleted'] = status.deleted attending, invited, userDetails = createAttendingAndInvitedAndUserDetailsJsonResponse(status) statusData['invited'] = invited statusData['attending'] = attending statusData['users'] = userDetails statusData['imageorientation'] = status.imageOrientation if status.imageUrl: statusData['imageurl'] = status.imageUrl if status.location: statusData['location'] = createLocationJson(status.location) if userProfile is not None: # if status.visibility == Status.VIS_FRIENDS_OF_FRIENDS or status.visibility == Status.VIS_PUBLIC: statusData['mutualfriends'] = UserProfile.getMutualFriends(status.user_id, userProfile.id) return statusData
def getNewData(request): response = dict() userid = request.REQUEST['userid'] since = request.REQUEST.get('since', None) if since: since = datetime.strptime(since, MICROSECOND_DATETIME_FORMAT) try: userProfile = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse("Invalid user id") newSince = datetime.now().strftime(MICROSECOND_DATETIME_FORMAT) pokes = getNewPokesData(userProfile, since) chats = getNewChatsData(userProfile, since) notifications = getNotificationsJson(userProfile, since) response['chats'] = chats response['newsince'] = newSince response['notifications'] = notifications response['success'] = True response['pokes'] = pokes return HttpResponse(json.dumps(response))
def update_user(self, application, commit=True): """ Update the UserProfile for the given application's user. Also detect changes in design fields, store them in instance, and notify us by e-mail. """ if hasattr(application.user, 'profile'): application.user.profile.full_name = self.cleaned_data['full_name'] else: application.user.profile = UserProfile( full_name=self.cleaned_data['full_name'], user_id=application.user.pk, ) if commit: with transaction.atomic(): application.user.profile.save() application.save() if self.restart_fields_changed(): messages.add_message(self.request, messages.INFO, "Thank you for submitting these changes - we will rebuild your instance to " "apply them, and email you to confirm once it is up to date.") # Notify us if settings.VARIABLES_NOTIFICATION_EMAIL: subject = 'Update required at instance {name}'.format( name=application.subdomain, ) template = get_template('registration/fields_changed_email.txt') text = template.render(dict( application=application, changed_fields=self.changed_data, )) sender = settings.DEFAULT_FROM_EMAIL dest = [settings.VARIABLES_NOTIFICATION_EMAIL] send_mail(subject, text, sender, dest)
def rsvpStatus(request): response = dict() userId = request.REQUEST['userid'] statusId = request.REQUEST['statusid'] attending = request.REQUEST['attending'] try: userProfile = UserProfile.getUser(userId) except UserProfile.DoesNotExist: return errorResponse('Invalid User') try: status = Status.getStatus(statusId) except Status.DoesNotExist: return errorResponse('Invalid Status') if attending == 'true' or attending == 'True': status.attending.add(userProfile) createAttendingStatusNotification(status, userProfile) sendAttendingStatusPushNotification(status, userProfile) elif attending == 'false' or attending == 'False': status.attending.remove(userProfile) else: return errorResponse("Invalid Attending value. Must be true or false") response['success'] = True return HttpResponse(json.dumps(response))
def editGroupName(request): response = dict() userid = request.REQUEST['userid'] groupName = request.REQUEST['groupname'] groupid = request.REQUEST['groupid'] try: userProfile = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse("Invalid user id") try: group = Group.objects.get(pk=groupid) except Group.DoesNotExist: return errorResponse("Invalid group id") if group.user != userProfile: return errorResponse("Group does not belong to user") group.name = groupName group.save() response['success'] = True return HttpResponse(json.dumps(response))
def view_profile(request, user_id): userprofile = UserProfile.get_for_user(request.user) donor = get_object_or_404(UserProfile, id=user_id) offers = donor.localoffer_set.filter_by_user(userprofile) return render_to_response_context(request, 'userprofile/userprofile.html', {'donor':donor, 'offers':offers})
def registerForPushNotifications(request): response = dict() userid = request.REQUEST['userid'] token = request.REQUEST['token'] platform = request.REQUEST['platform'] try: userProfile = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse("User does not exist") if platform == 'ios': try: device = APNSDevice.objects.get(registration_id=token) device.user = userProfile device.save() except APNSDevice.DoesNotExist: device = APNSDevice.objects.create(user=userProfile, registration_id=token) elif platform == 'android': try: device = GCMDevice.objects.get(registration_id=token) device.user = userProfile device.save() except GCMDevice.DoesNotExist: device = GCMDevice.objects.create(user=userProfile, registration_id=token) else: return errorResponse("platform must be ios or android") response['success'] = True return HttpResponse(json.dumps(response))
def setSetting(request): response = dict() userid = request.REQUEST['userid'] key = request.REQUEST['key'] value = request.REQUEST['value'] if key != 'statusradius' and key != 'imboredtext': return errorResponse("unknown key. Must be statusradius or imboredtext") try: userProfile = UserProfile.getUser(userid) except UserProfile.DoesNotExist: return errorResponse("User does not exist") try: setting = userProfile.settings.get(key=key) setting.value = value setting.save() except Setting.DoesNotExist: Setting.objects.create(user=userProfile, value=value, key=key) response['success'] = True return HttpResponse(json.dumps(response))
class SubmissionCreateAndReviewForm(SubmissionReviewForm): submission_time = forms.DateTimeField() students = forms.ModelMultipleChoiceField( queryset=UserProfile.objects.none(), required=False) students_by_student_id = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda student_id: UserProfile.get_by_student_id(student_id), choices=[(p.student_id, p.student_id) for p in UserProfile.objects.none()], required=False) students_by_email = forms.TypedMultipleChoiceField( empty_value=UserProfile.objects.none(), coerce=lambda email: UserProfile.get_by_email(email), choices=[(u.email, u.email) for u in User.objects.none()], required=False) def __init__(self, *args, **kwargs): super(SubmissionCreateAndReviewForm, self).__init__(*args, **kwargs) self.fields["students"].queryset = \ UserProfile.objects.all() #self.exercise.course_instance.get_student_profiles() self.fields["students_by_student_id"].choices = \ [ (p.student_id, p.student_id) for p in UserProfile.objects.all() #self.exercise.course_instance.get_student_profiles() ] self.fields["students_by_email"].choices = \ [ (u.email, u.email) for u in User.objects.all() ] def clean(self): self.cleaned_data = super(SubmissionCreateAndReviewForm, self).clean() n = 0 if self.cleaned_data.get("students"): n += 1 if self.cleaned_data.get("students_by_student_id"): n += 1 if self.cleaned_data.get("students_by_email"): n += 1 if n == 0: raise forms.ValidationError( _("One of the student fields must not be blank: students, students_by_student_id, students_by_email" )) if n > 1: raise forms.ValidationError( _("Only one student field can be given: students, students_by_student_id, students_by_email" )) return self.cleaned_data
def notify_editors(sender, instance, created, **kwargs): if created: editors = list(UserProfile.get_by_rol(settings.BLOG_EDITOR_ROL_ID).values_list("user__email",flat=True)) msg = "Se ha creado una nueva entrada.\nPuedes verla en http://thechurchofhorrors.com%s" % instance.get_admin_url() send_mail('[TheChurchofHorrors] Nueva entrada', msg, settings.BLOG_DEFAULT_SENDER, editors, fail_silently=False)
def show_avatar(value): ''' 显示头像 ''' if value.is_authenticated: try: UserProfile.objects.get(user=value) #user不是超级用户但是已经注册 avatar = UserProfile.objects.get(user=value).picture except UserProfile.DoesNotExist: #user是超级用户或第三方用户但是没有注册 newuser = UserProfile(user_id=value.id, width_field=100, height_field=100) newuser.save() avatar = newuser.picture return avatar.url
def teacher_profile_add(request): if request.method == 'POST': a = Teacher() a.image = request.FILES['img'] a.name = request.POST['name'] a.teacher_id = name = request.POST['teacherid'] a.email_id = number = request.POST['emailid'] a.address = request.POST['address'] a.department = Department.objects.get(name=request.POST['dept']) a.save() user = User.objects.create_user(username=a.teacher_id, password=a.teacher_id) x = UserProfile() x.user = User.objects.get(username=a.teacher_id) x.is_teacher = 'True' x.uid = a.teacher_id x.save() #user.username = a.roll_number #user.password = a.roll_number #user.save() auth.authenticate(username=a.teacher_id, password=a.teacher_id) return render(request, 'dashboard/profile/teacher_profile_add.html') else: dept = Department.objects.all() return render(request, 'dashboard/profile/teacher_profile_add.html', {'departments': dept})
def create_user(self, application, commit=True): """ Create related User and UserProfile instance for the given BetaTestApplication. """ user = User( username=self.cleaned_data['username'], email=self.cleaned_data['email'], ) user.set_password(self.cleaned_data['password']) profile = UserProfile(full_name=self.cleaned_data['full_name'], ) if commit: with transaction.atomic(): user.save() profile.user_id = user.pk application.user_id = user.pk profile.save() application.save()
def test_auth_get_with_token(self): self.assertIsNone(UserProfile.objects.first()) user = UserProfile.create_from_google_info(self.user_info) extra = {'HTTP_AUTHORIZATION': 'Token {}'.format(user.token)} response = self.client.get(self.base_url, **extra) self.assertEqual(response.status_code, 200) user = response.data self.assertIsNotNone(user) self.assertEqual(user["name"], self.user_info["name"]) self.assertEqual(user["picture"], self.user_info["picture"])
def edit_profile(request): context = RequestContext(request) try: user_profile = UserProfile.objects.get(user=request.user) except UserProfile.DoesNotExist: user_profile = UserProfile(user=request.user) if request.method == 'POST': edit_form = ProfileForm(request.POST) if edit_form.is_valid(): data = edit_form.cleaned_data user_profile.full_name = data['full_name'] user_profile.bio = data['bio'] user_profile.save() return HttpResponseRedirect( reverse('userprofile.views.profile', args=(), kwargs={'username': request.user.username})) else: print edit_form.errors else: edit_form = ProfileForm({ 'full_name': user_profile.full_name, 'bio': user_profile.bio }) context_dict = {'edit_form': edit_form} return render_to_response('userprofile/edit.html', context_dict, context)
def create_user(self, application, commit=True): """ Create related User and UserProfile instance for the given BetaTestApplication. """ user = User( username=self.cleaned_data['username'], email=self.cleaned_data['email'], ) user.set_password(self.cleaned_data['password']) profile = UserProfile( full_name=self.cleaned_data['full_name'], accepted_privacy_policy=timezone.now(), subscribe_to_updates=self.cleaned_data['subscribe_to_updates'], ) if commit: with transaction.atomic(): user.save() profile.user_id = user.pk application.user_id = user.pk profile.save() application.save()
def createInst(self, postrequest, numofinst): insts = [] uprof = UserProfileOPS() for i in xrange(numofinst): n_str = str(i) + '-' upass = uprof.generatenewpass( ) # uretilen parola olusturulan kullaniciya gonderilecek. inst = User(first_name=postrequest[n_str + 'first_name'], last_name=postrequest[n_str + 'last_name'], email=postrequest[n_str + 'email'], username=postrequest[n_str + 'email'], password=upass) inst.save() instprof = UserProfile(job=postrequest[n_str + 'job'], title=postrequest[n_str + 'title'], organization=postrequest[n_str + 'organization'], is_instructor=True, user=inst) instprof.save() insts.append(instprof) return insts
def post(self, request): payload = {"access_token": request.data.get("token")} # validate token try: res = requests.get(GOOGLE_VALIDATE_URL, params=payload) except HTTPError as e: content = {"error": "Invalid Google token" + str(e)} return Response(content, status=400) if not res.ok: content = {"error": "Invalid Google token"} return Response(content, status=401) data = json.loads(res.text) # create user if doesn't exist try: user = User.objects.get(email=data["email"]) except User.DoesNotExist: user = User( username=data["email"], password=make_password( BaseUserManager().make_random_password()), email=data["email"], first_name=data["given_name"], last_name=data["family_name"], ) user.save() profile = UserProfile(picture=data['picture'], user=user) profile.save() refresh_token = RefreshToken.for_user( user) # generate token without username & password response = { "id": user.id, "email": user.email, "access_token": str(refresh_token.access_token), "refresh_token": str(refresh_token) } return Response(response)
def create(self, validated_data): user_dict = validated_data['user'] tag_dict = validated_data['tag'] first_in_required = [f for f in self._required if f in user_dict][0] try: user = { 'id': lambda: UserProfile.objects.get(user__id=user_dict['id']), 'student_id': lambda: UserProfile.get_by_student_id(user_dict['student_id']), 'username': lambda: UserProfile.objects.get(user__username=user_dict[ 'username']), 'email': lambda: UserProfile.get_by_email(user_dict['email']), }[first_in_required]() tag = UserTag.objects.get( slug=tag_dict['slug'], course_instance=self.context['course_id']) except UserTag.DoesNotExist: # 404 with description raise exceptions.NotFound( "Tag with slug {slug} was not found".format( slug=tag_dict['slug'])) except UserProfile.DoesNotExist: raise exceptions.NotFound( "User identified with {key}:{value} was not found".format( key=first_in_required, value=user_dict[first_in_required])) obj, created = UserTagging.objects.set(user, tag) if not created: raise serializers.ValidationError( "User {user} already has tag {slug}".format( user=user.user.username, slug=tag.slug, )) return obj
def update_user(self, application, commit=True): """ Updated the UserProfile for the given application's user. """ if hasattr(application.user, 'profile'): application.user.profile.full_name = self.cleaned_data['full_name'] else: application.user.profile = UserProfile( full_name=self.cleaned_data['full_name'], user_id=application.user.pk, ) if commit: with transaction.atomic(): application.user.profile.save() application.save()
def enroll_from_sis(self) -> int: """ Enroll students based on the participants information in Student Info System. If student has removed herself in SIS, she will also be marked as removed in A+. Returns ------- Number of students enrolled based on this call. -1 if there was problem accessing SIS. """ from .sis import get_sis_configuration, StudentInfoSystem from .cache.menu import invalidate_content sis: StudentInfoSystem = get_sis_configuration() if not sis: return -1 count = 0 try: participants = sis.get_participants(self.sis_id) except Exception as e: logger.exception(f"Error in getting participants from SIS.") return -1 for i in participants: try: profile = UserProfile.get_by_student_id(i) if self.enroll_student(profile.user, from_sis=True): count = count + 1 except UserProfile.DoesNotExist: # This is a common scenario, if the user has enrolled in SIS, but not # yet logged in to A+, then the user profile does not exist yet. pass # Remove SIS-enrolled students who are not anymore in SIS participants, # for example, because they have first enrolled in SIS, but then # unenrolled themselves. students = self.all_students.filter(enrollment__from_sis=True) to_remove = students.exclude(student_id__in=participants) qs = Enrollment.objects.filter(user_profile__in=to_remove, course_instance=self) qs.update(status=Enrollment.ENROLLMENT_STATUS.REMOVED) for e in qs: invalidate_content(Enrollment, e) return count
def test_auth_patch(self): self.assertIsNone(UserProfile.objects.first()) user = UserProfile.create_from_google_info(self.user_info) extra = { 'HTTP_AUTHORIZATION': 'Token {}'.format(user.token), 'CONTENT_TYPE': 'application/json', } update_data = dict(name="John Kim Chen") response = self.client.patch( self.base_url, json.dumps(update_data), **extra ) self.assertEqual(response.status_code, 200) user = response.data self.assertEqual(user["name"], update_data["name"])
def handle(self, *args, **options): try: course_instance = CourseInstance.objects.get( id=options['course_instance_id']) except CourseInstance.DoesNotExist: raise CommandError( f"CourseInstance id={options['course_instance_id']} does not exist!" ) nonexistent_ids = [] counter = 0 try: with open(options['student_list_file'], 'r') as f: for row in f: identifier = row.strip() if identifier: if options['email']: user = User.objects.filter( email=identifier, ).exclude( userprofile__student_id__isnull=True, ).exclude( userprofile__student_id='', ).first() if user is None: nonexistent_ids.append(identifier) elif course_instance.enroll_student(user): counter += 1 else: try: profile = UserProfile.get_by_student_id( identifier) if course_instance.enroll_student( profile.user): counter += 1 except UserProfile.DoesNotExist: nonexistent_ids.append(identifier) except FileNotFoundError: raise CommandError( f"The student list file {options['student_list_file']} was not found!" ) except OSError as e: self.print_results(course_instance, counter, nonexistent_ids) raise CommandError("Error in reading the student list file: " + str(e)) self.print_results(course_instance, counter, nonexistent_ids)
def post(self, request): # Get User from Token user = request.user # Create Instance of User Profile profile = UserProfile(user=user) # Serialize Data profile_serializer = CreateUserProfileSerializer(profile, data=request.data) # Check User Data is valid or not if profile_serializer.is_valid(): # Save Data to Model profile_serializer.save() # Response User with serialize data return Response(profile_serializer.data, status=status.HTTP_201_CREATED) else: return Response(profile_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(request): if isinstance(request.user, UserProfile): return Response(data=UserSerializer(request.user).data) # 2nd step of Oauth if 'code' in request.GET: code = request.GET.get('code') user_info = get_user_info(code) try: user = UserProfile.objects.get(google_email=user_info["email"]) except UserProfile.DoesNotExist: user = UserProfile.create_from_google_info(user_info) else: user.update_with_google_info(user_info) return Response(data=UserSerializer(user).data) return Response({"client_id": GOOGLE_CLIENT_ID}, status=status.HTTP_403_FORBIDDEN)
def form_valid(self, form): """ This method is called when valid form data has been POSTed. The user must be logged once it has been created. """ myresponse = super(CreateView, self).form_valid(form) username = self.request.POST['username'] password = self.request.POST['password1'] user = authenticate(username=username, password=password) if user is not None: login(self.request, user) user.userprofile = UserProfile(website='') user.userprofile.save() else: raise Exception('User is not registered') return myresponse
def student_profile_add(request): if request.method == 'POST': a = Student() a.name = request.POST['name'] a.image = request.FILES['img'] a.academic_year = AcademicYear.objects.get( year=request.POST['academic_year']) a.course = Course.objects.get(name=request.POST['course']) a.semester = Semester.objects.get(number=request.POST['semester']) a.roll_number = request.POST['roll_number'] a.admission_number = request.POST['admission_number'] a.registration_number = request.POST['registration_number'] a.phone_number = request.POST['phone_number'] a.email_id = request.POST['email_id'] a.address = request.POST['address'] a.save() user = User.objects.create_user(username=a.roll_number, password=a.roll_number) x = UserProfile() x.user = User.objects.get(username=a.roll_number) x.is_student = 'True' x.uid = a.roll_number x.save() #user.username = a.roll_number #user.password = a.roll_number #user.save() auth.authenticate(username=a.roll_number, password=a.roll_number) return render(request, 'dashboard/profile/student_select.html') else: acyrs = AcademicYear.objects.all() crs = Course.objects.all() sem = Semester.objects.all() return render(request, 'dashboard/profile/student_profile_add.html', { 'academic_years': acyrs, 'courses': crs, 'semesters': sem })