Esempio n. 1
0
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()
Esempio n. 2
0
def make_user(**kwargs):
    newUser = User(**kwargs)
    newUser.set_password(kwargs['password'])
    newUser.save()
    newProfile = UserProfile(user=newUser)
    newProfile.save()
    return newUser
Esempio n. 3
0
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()
Esempio n. 4
0
 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
Esempio n. 5
0
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)
Esempio n. 6
0
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})
Esempio n. 7
0
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})
Esempio n. 8
0
 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
Esempio n. 9
0
def create_twitter_profile(id, oauth_token, oauth_token_secret, name):
    profile = UserProfile()
    profile.user_id = id
    profile.oauth_token = oauth_token
    profile.oauth_secret = oauth_token_secret
    profile.screen_name = name
    profile.save()
Esempio n. 10
0
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)
Esempio n. 11
0
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 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))
Esempio n. 13
0
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,
    })
Esempio n. 14
0
 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
Esempio n. 15
0
 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()
Esempio n. 16
0
	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
Esempio n. 17
0
    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)
Esempio n. 18
0
 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))
Esempio n. 19
0
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
Esempio n. 20
0
 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()
Esempio n. 21
0
    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.set_password(self.cleaned_data['password1'])
        profile = UserProfile(user=user)

        profile.user = user
        profile.user.self_description = "self_description"
        profile.user.line_of_work = "line_of_work"
        profile.user.hobbies = "hobbies"
        profile.user.owns_car = "owns_car"
        profile.user.vehicle_model = "vehicle_model"

        if commit:
            user.save()
            profile.save()

        return user
Esempio n. 22
0
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
Esempio n. 23
0
def user_details(strategy, details, response, is_new=False,
                 user=None, *args, **kwargs):
    """Update user details using data from provider."""
    if user:
        if is_new:

            # get special extra data
            # if strategy.backend.__class__.__name__ == 'TwitterOAuth':
                # twitter_data = {}
            # elif strategy.backend.__class__.__name__ == 'FacebookOAuth2':
                # fb_data = {
                # 'locale': response['locale'],
                # }
            # elif strategy.backend.__class__.__name__ == 'GithubOAuth2':

            profile = UserProfile()
            profile.user = user
            profile.picture = get_user_avatar()
            profile.save()
Esempio n. 24
0
def edit_user(request, id=None):
    if id:
        action = "edit"
        userprofile = get_object_or_404(UserProfile, id=id)
        user = userprofile.user
        initial = { 'username':user.username,
                    'name':userprofile.name,
                    'password':"",
                    'email':user.email,
                    'phone_number':userprofile.phone_number,
                    'info':userprofile.info,
                    'is_staff':user.is_staff,
                  }
    else:
        action = "add"
        userprofile = None
        initial = None
    if request.POST:
        form = UserForm(request.POST, instance=userprofile)
        if form.is_valid():
            if userprofile:
                user = userprofile.user
            else:
                userprofile = UserProfile()
                user = User()
                userprofile.user = user
                
            userprofile.user.username = form.cleaned_data['username']
            userprofile.name = form.cleaned_data['name']
            userprofile.user.email = form.cleaned_data['email']
            userprofile.phone_number = form.cleaned_data['phone_number']
            userprofile.info = form.cleaned_data['info']
            userprofile.user.is_staff = form.cleaned_data['is_staff']
            if form.cleaned_data['password']:
                userprofile.user.set_password(form.cleaned_data['password'])
            user.save()
            userprofile.user = user
            userprofile.save()
            request.user.message_set.create(message="User '%s' was %sed." % (userprofile.name, action))
            return HttpResponseRedirect("/user/manage/")
    else:
        form = UserForm(initial=initial, instance=userprofile)
    return render_to_response_context(request, 'userprofile/manage/edit.html', {'form':form, 'action':action})
Esempio n. 25
0
def edit(request):
  if request.method == 'POST': # If the form has been submitted...
    form = UserProfileForm(request.POST) # A form bound to the POST data
  
    if form.is_valid(): 
      userprofile = UserProfile()
      userprofile.user = request.user
      userprofile.firstname = form.cleaned_data['firstname']
      userprofile.lastname = form.cleaned_data['lastname']
      userprofile.number = form.cleaned_data['number']
      userprofile.serie = form.cleaned_data['serie']
      userprofile.sexe = form.cleaned_data['sexe']
      userprofile.phoneNumber = form.cleaned_data['phoneNumber']

      userprofile.save()
      return redirect('userprofile.views.display') # Redirect after POST
    else:
      return render(request,
        'userprofile/userprofile_edit.html', {
            'form': form,
          }
        )
  else:
    try:
      userprofile = UserProfile.objects.get(pk=request.user)
      form = UserProfileForm({
        'firstname': userprofile.firstname,
        'lastname': userprofile.lastname,
        'number': userprofile.number,
        'serie': userprofile.serie,
        'sexe': userprofile.sexe,
        'phoneNumber': userprofile.phoneNumber,
      })
    except Exception as ex:
      print ex
      form = UserProfileForm()

    return render(request, 
            'userprofile/userprofile_edit.html', {
                'form': form,
              }
            )
Esempio n. 26
0
 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()
Esempio n. 27
0
    def register(self, request, **cleaned_data):
        username, email, password, first_name, last_name = cleaned_data['username'], cleaned_data['email'], cleaned_data['password1'], cleaned_data['first_name'], cleaned_data['last_name']
        theuser = UserModel().objects.create_user(username = username,
            password = password,
            email = email,
            first_name = first_name,
            last_name = last_name
        )
        theuser.save()
        
        profile = UserProfile(user = theuser, location = cleaned_data['location'], career = cleaned_data['career'])
        profile.save()
        #(username, email, password, first_name, last_name)

        new_user = authenticate(username=username, password=password)
        login(request, new_user)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user
    def getFacebookUserFromAuthKey(cls, facebookAuthKey, device):
        graph = facebook.GraphAPI(facebookAuthKey)
        profile = graph.get_object("me")
        facebookId = profile['id']

        if 'email' in profile:
            username = str(profile['email'])
        elif not 'email' in profile:
            if 'first_name' in profile and 'last_name' in profile:
                username = str(profile['first_name']) + str(profile['last_name'])
            elif 'name' in profile:
                username = str(profile['name'])
            elif 'first_name' in profile:
                username = str(profile['first_name'])
            elif 'last_name' in profile:
                username = str(profile['last_name'])

        newUser = False
        try:
            userProfile = UserProfile.objects.get(facebookUID=facebookId)
        except UserProfile.DoesNotExist:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                username = username[:30]
                firstName = str(profile['first_name'])[:30]
                lastName = str(profile['last_name'])[:30]
                user = User(username=username, first_name=profile['first_name'],
                            last_name=profile['last_name'], password=0)
                if 'email' in profile:
                    user.email = str(profile['email'])
                else:
                    user.email = ''

                user.save()
                newUser = True

            userProfile = UserProfile(facebookUID=facebookId, user=user, device=device)
            userProfile.save()

        return FacebookProfile(userProfile, facebookAuthKey), newUser
Esempio n. 29
0
def facebook(request):
    params = {
        "client_id": settings.FACEBOOK_APP_ID,
        "redirect_uri": "http://localhost:8000/facebook/",
        "client_secret": settings.FACEBOOK_SECRET_KEY,
        "code": request.GET["code"],
    }

    http = httplib2.Http(timeout=15)
    response, content = http.request("https://graph.facebook.com/oauth/access_token?%s" % urllib.urlencode(params))

    # Find access token and expire (this is really gross)
    params = content.split("&")
    ACCESS_TOKEN = params[0].split("=")[1]
    EXPIRE = params[1].split("=")[1]

    # Get basic information about the person
    response, content = http.request("https://graph.facebook.com/me?access_token=%s" % ACCESS_TOKEN)
    data = json.loads(content)
    # Try to find existing profile, create a new user if one doesn't exist
    try:
        profile = UserProfile.objects.get(facebook_uid=data["id"])
    except UserProfile.DoesNotExist:
        user = User.objects.get_or_create(
            username=data["username"], first_name=data["first_name"], last_name=data["last_name"]
        )
        user = User.objects.get(username=data["username"])
        profile = UserProfile(user=user)
        profile.facebook_uid = data["id"]

    # Update token and expire fields on profile
    profile.facebook_access_token = ACCESS_TOKEN
    profile.facebook_access_token_expires = EXPIRE
    profile.save()
    # Authenticate and log user in
    # user = authenticate(username=profile.user.username, password='')
    user = profile.user
    user.backend = "django.contrib.auth.backends.ModelBackend"
    auth_login(request, user)

    return HttpResponseRedirect("/")
Esempio n. 30
0
 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()
Esempio n. 31
0
 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
Esempio n. 32
0
def edit(request):
    if request.method == 'POST':  # If the form has been submitted...
        form = UserProfileForm(request.POST)  # A form bound to the POST data

        if form.is_valid():
            userprofile = UserProfile()
            userprofile.user = request.user
            userprofile.firstname = form.cleaned_data['firstname']
            userprofile.lastname = form.cleaned_data['lastname']
            userprofile.number = form.cleaned_data['number']
            userprofile.serie = form.cleaned_data['serie']
            userprofile.sexe = form.cleaned_data['sexe']
            userprofile.phoneNumber = form.cleaned_data['phoneNumber']

            userprofile.save()
            return redirect('userprofile.views.display')  # Redirect after POST
        else:
            return render(request, 'userprofile/userprofile_edit.html', {
                'form': form,
            })
    else:
        try:
            userprofile = UserProfile.objects.get(pk=request.user)
            form = UserProfileForm({
                'firstname': userprofile.firstname,
                'lastname': userprofile.lastname,
                'number': userprofile.number,
                'serie': userprofile.serie,
                'sexe': userprofile.sexe,
                'phoneNumber': userprofile.phoneNumber,
            })
        except Exception as ex:
            print ex
            form = UserProfileForm()

        return render(request, 'userprofile/userprofile_edit.html', {
            'form': form,
        })
Esempio n. 33
0
    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)
Esempio n. 34
0
def register(request):
    registered = False

    if request.method == 'POST':
        user_form = UserRegForm(data=request.POST)

        if user_form.is_valid():
            user = user_form.save()

            user.set_password(user.password)
            user.save()

            user_profile = UserProfile(user=user)
            user_profile.save()

            registered = True

        else:
            print user_form.errors
    else:
        user_form = UserRegForm()

    return render(request, 'authenticate/register.html', {'user_form': user_form, 'registered': registered})
def create_account(request):
    """
    :param request: POST method
                        json format '{"username": "******",
                                    "email":"email_value" ,
                                    "password": "******"""
    response=dict()
    response['success']=False
    response['message']=""
    try:
        username = request.POST['username']
        password = request.POST['password']
        email= request.POST['email']

        if User.objects.filter(username=username).exists():
            return error_response("username exists")

        if User.objects.filter(email=email).exists():
            return error_response("email exists")

        new_user = User.objects.create_user(username=username,
                                            email=email,
                                            password=password)
        token=Token.objects.create(user=new_user)
        new_user_profile = UserProfile(user = new_user)
        new_user_profile.save()

        response['success']=True
        response['message']="success"
        response['token']=token.key

    except ValueError:
        return error_response("Please provide username, password and email")

    return package_handle(response)
Esempio n. 36
0
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
        })
Esempio n. 37
0
def user_details(strategy,
                 details,
                 response,
                 is_new=False,
                 user=None,
                 *args,
                 **kwargs):
    """Update user details using data from provider."""
    if user:
        if is_new:

            # get special extra data
            # if strategy.backend.__class__.__name__ == 'TwitterOAuth':
            # twitter_data = {}
            # elif strategy.backend.__class__.__name__ == 'FacebookOAuth2':
            # fb_data = {
            # 'locale': response['locale'],
            # }
            # elif strategy.backend.__class__.__name__ == 'GithubOAuth2':

            profile = UserProfile()
            profile.user = user
            profile.picture = get_user_avatar()
            profile.save()
Esempio n. 38
0
 def auth_user(self):
     user = UserProfile(name="Test user", google_email="*****@*****.**")
     user.save()
     self.client.defaults['HTTP_AUTHORIZATION'] = 'Token {}'.format(
         user.token)
Esempio n. 39
0
import os
os.environ['DJANGO_SETTINGS_MODULE']='django_forum.settings'

import django
django.setup()

from userprofile.models import UserProfile
from django.contrib.auth.models import User

for i in User.objects.all():
    p=UserProfile(user=i)
    p.save()
Esempio n. 40
0
def add_employee(request):
	response = {}
	response.update({'employee_type_choices':employee_type_choices})

	if request.method == 'POST':

		username = request.POST['username']
		password = request.POST['password']

		try:
			User.objects.get(username__iexact=username)
		except:
			user = User()
			user.username = username
			user.set_password(password)
			user.save()
		else:
			response.update({'error':True})
			response.update({'error_message':'Username already exists, please use another username'})
			return render(request, 'userprofile/add_employee.html', response)

		# initialize userprofile object
		userprofile = UserProfile()
		userprofile.user = user
		userprofile.full_name = request.POST.get('full_name', '')
		userprofile.gender = request.POST.get('gender', '')
		dob = request.POST.get('dob', '')
		if dob:
			userprofile.dob = datetime.datetime.strptime(dob, '%m/%d/%Y')
		userprofile.father = request.POST.get('father', '')
		userprofile.mother = request.POST.get('mother', '')
		userprofile.email = request.POST.get('email', '')
		userprofile.present_address = request.POST.get('present_address', '')
		userprofile.permanent_address = request.POST.get('permanent_address', '')
		userprofile.mobile = request.POST.get('mobile', '')
		userprofile.landline = request.POST.get('landline', '')
		userprofile.maritial_status = request.POST.get('maritial_status', '')
		userprofile.user_type = 'staff'
		userprofile.save()
		try:
			userprofile.save()
		except:
			user.delete()
			response.update({'error':True})
			return render(request, 'userprofile/add_employee.html', response)

		# initialize employee object
		employee = Employee()
		employee.userprofile = userprofile
		employee.employee_type = request.POST.get('employee_type', '')
		employee.date_joined = datetime.datetime.strptime(request.POST.get('date_joined', ''), '%m/%d/%Y')

		try:
			employee.save()
		except:
			user.delete()
			response.update({'error':True})
			return render(request, 'userprofile/add_employee.html', response)

		response.update({'success':True})

	return render(request, 'userprofile/add_employee.html', response)
Esempio n. 41
0
# coding=UTF-8
Esempio n. 42
0
def create_profile(sender, **kwargs):
    user = kwargs["instance"]
    if kwargs["created"]:
        profile = UserProfile(user=user, displayname=user.username)
        profile.save()
Esempio n. 43
0
def joingame(request, game_id, slug):
    game = get_object_or_404(Pamplesneak, pk=game_id)
    user = request.user

    word_list = []
    for i in range(0,game.word_bank_size):
        word_list.append(random.choice(WORDS))

    try:
       player = Player.objects.filter(game=game).get(name=user.username)
    except Player.DoesNotExist:
       player = None
    
    if not player:
        new_player = Player(game=game, user=user, name=user.username)
        new_player.save()
        player = new_player

    try:
        user_profile = UserProfile.objects.get(user=user)
    except:
        user_profile = UserProfile(user=user)
        user_profile.save()

    try:
        pample_info = PamplesneakInfo.objects.get(user=user_profile)
    except:
        pample_info = PamplesneakInfo(user=user_profile)
        pample_info.save()

    pample_info.current_game = player
    pample_info.previous_games.add(player)
    pample_info.save()

    game.number_of_players = game.getCurrentPlayers()
    game.save()

    if request.method == "POST":
        all_players_query = Player.objects.filter(game=game)
        players_query = all_players_query.exclude(id=player.id)
        players_dict = {}
        for p in players_query:
            players_dict[p.id] = p.name
        form = MessageSender(players_dict, request.POST)
        print form.is_bound
        if form.is_valid():
            """gets form data"""
            word = form.cleaned_data['word']
            player_id = form.cleaned_data['players']
            to_player = Player.objects.get(id=player_id)

            """attaches sender signature to object"""
            if form.cleaned_data['send_anonymously'] == True:
                created_by = None
            else:
                created_by = player

            new_word = GameWord(word=word, player=to_player, game=player.game, send_to = player, created_by = created_by)
            new_word.save()

            args = {}
            args['form'] = form
            args['word'] = random.choice(WORDS)
            args['word_list'] = word_list
            args['word_bank_size'] = game.word_bank_size
            args['game'] = game
            args['player'] = player
            args['players'] = all_players_query.order_by('-succesful_sneaks')
            args['player_count'] = players_query.count()
            return HttpResponseRedirect('')
    else:
        all_players_query = Player.objects.filter(game=game)
        players_query = all_players_query.exclude(id=player.id)
        players_dict = {}
        for p in players_query:
            players_dict[p.id] = p.name
        form = MessageSender(players_dict)
    args = {}
    args['form'] = form
    args['word'] = random.choice(WORDS)
    args['word_list'] = word_list
    args['word_bank_size'] = game.word_bank_size
    args['game'] = game
    args['player'] = player
    args['players'] = all_players_query.order_by('-succesful_sneaks')
    args['player_count'] = players_query.count()
    return render_to_response('pamplesneak/ingame.html', args, context_instance=RequestContext(request))