Example #1
0
def register(request):
    if request.method == 'POST':
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            pass
        else:
            return redirect('/')

        if username and password:
            user = User(
                username=username,
            )
            user.set_password(password)
            user.save()
            print 'saved'

            user_pro = UserProfile(
                user=user,
            )
            user_pro.save()
            print 'saved'

            user_url = '/users/%s' % user.id
            return redirect('/welcome')

    return redirect('/')
Example #2
0
def index(request):
  if request.method == 'POST':
    form = SignUpForm(request.POST)
    if form.is_valid():
      data = form.cleaned_data
      user = User(username = data['username'],
          password = data['password'],
          first_name = data['first_name'],
          last_name = data['last_name'],
          email = data['email'],
          )
      user.is_staff=True
      user.is_superuser=True
      user.save()
      profile = UserProfile(user = user,
          phone = data['phone'],
          card_bill_addr = data['card_bill_addr'],
          card_bill_city = data['card_bill_city'],
          card_bill_state = data['card_bill_state'],
          card_bill_zip = data['card_bill_zip']
          )
      profile.save()
      return redirect('/creditcard/')
  else:
    form = SignUpForm()
  context = RequestContext(request, {'form': form})
  return render_to_response('index.html', context)
Example #3
0
    def post(self):
        """
        """
        new_profile = self.current_userprofile.to_python()

        # Apply each argument we accept to the new structure
        new_profile["name"] = self.get_argument("name", None)
        new_profile["bio"] = self.get_argument("bio", None)
        new_profile["location_text"] = self.get_argument("location_text", None)
        new_profile["avatar_url"] = self.get_argument("avatar_url", None)
        new_profile["email"] = self.get_argument("email", None)

        # Help a user out if they didn't put the "http" in front
        website = self.get_argument("website", None)
        if not website.startswith("http"):
            website = "http://%s" % (website)
        new_profile["website"] = website

        # Save values if they pass validation
        try:
            new_up = UserProfile(**new_profile)
            new_up.validate()
            save_userprofile(self.db_conn, new_up)
            self._current_userprofile = new_up
        except Exception, e:
            # TODO handle errors nicely
            raise
Example #4
0
def user_register(request):
	user_type = request.session.get("user_type", "")
	if user_type == "student":
		render_template = "student_signup.html"
	elif user_type == "coach":
		render_template = "coach_signup.html"
	else:
		return HttpResponseRedirect('/user/login')
	if request.method == 'POST':
		form = RegisterForm(request.POST)
		if form.is_valid():
			username = form.cleaned_data['username']
			email = form.cleaned_data.get('email', '')
			password = form.cleaned_data['password']
			region = form.cleaned_data.get('region', '')
			phone = form.cleaned_data.get('phone', '')
			qq = form.cleaned_data.get('qq', '')
			skype = form.cleaned_data.get('skype', '')
			new_user = User.objects.create_user(username, email, password)
			if new_user:
				user_profile = UserProfile(user = new_user, region = region, phone = phone, qq = qq, skype = skype, user_type = user_type)
				user_profile.save()
				login_user = authenticate(username = username, password = password)
				login(request, login_user)
				request.session["user_type"] = None
				return HttpResponseRedirect('/user')
		
		return render(request, render_template, {'form': form})

	form = RegisterForm()
	return render(request, render_template, {'form': form})
Example #5
0
 def save(self, facebook_data):
     new_user = User.objects.create(
         username=self.cleaned_data['email'],
         email=self.cleaned_data['email']
     )
     new_user.first_name = facebook_data['first_name']
     new_user.last_name = facebook_data['last_name']
     
     new_user.save()
     new_user.set_unusable_password()
     new_username = int(new_user.id) + 1000000
             
     # set network for the user after registration
     # todo: make it universal for all universities using email pattern        
     network = Network.objects.get(id=1)
     
     profile = UserProfile(
         user=new_user,
         username=new_username,
         network=network
     )
     profile.save()
     
     wallet = Wallet(user=new_user)
     wallet.save()
     
     notif_setting = NotificationSettings(user=new_user)
     notif_setting.save()
             
     # send email confirmation
     EmailConfirmation.objects.send_confirmation(self.cleaned_data['email'], profile)
     
     return new_user
Example #6
0
def signup(request):
    #http://stackoverflow.com/questions/21107655/using-django-registration-with-a-flat-ui-template
    #http://stackoverflow.com/questions/2339369/how-can-i-override-the-django-authenticationform-input-css-class
    #http://stackoverflow.com/questions/1453488/how-to-markup-form-fields-with-div-class-field-type-in-django/1504903#1504903
    context = RequestContext(request)

    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save()
        user.set_password(user.password)

        #created django user
        user.save()

        #created racehub user, link django user to it
        new_racehub_user = UserProfile(user=user)
        new_racehub_user.save()

        registered = True

    else:
        user_form = UserForm()

    context_dict = {'user_form': user_form, 'registered': registered}

    return render_to_response('signup.html', context_dict, context)
Example #7
0
def email_signup(request):
    """
    On POST, create a User and UserProfile for the user, or error. On GET, render the sign up page
    """
    if request.method == "POST":
        email = request.POST.get('email')
        password = request.POST.get('password')
        password_confirm = request.POST.get('password_confirm')

        if not unique_user(email):
            messages.add_message(request, messages.ERROR, 'That email is already registered.')
            return redirect('/accounts/signup')

        if not valid_email_address(email):
            messages.add_message(request, messages.ERROR, 'Invalid email address.')
            return redirect('/accounts/signup')

        valid_pw = check_valid_password(password, password_confirm)
        if not valid_pw:
            messages.add_message(request, messages.ERROR, 'Invalid password.')
            return redirect('/accounts/signup')

        user = User.objects.create_user(username_md5(email), email, password)
        user_profile = UserProfile(user=user)
        user_profile.save()
        auth_user = authenticate(username=username_md5(email), password=password)
        dj_login(request, auth_user)
        return redirect('/subject_preferences')
    else:
        return render(request, 'accounts/signup.html')
Example #8
0
def signup_display(request):
        #return render(request, 'signup.html', {'page_title': 'Sign Up', })
        if request.method == 'POST':
            request_username = request.POST.get('username','')
            request_password = request.POST.get('password','')
            request_psw_confirm = request.POST.get('psw_confirm')
            request_email = request.POST.get('email')
            
            if request_password != request_psw_confirm:
                return render(request, 'signup.html', {'page_title': 'Sign Up', 'errors': '1' })
                
            if User.objects.filter(username = request_username).exists() or User.objects.filter(email = request_email).exists():
                return render(request, 'signup.html', {'page_title': 'Sign Up', 'errors': '2' })
                
            new_user = User.objects.create_user(request_username, request_email, request_password)
            new_user.save()
            new_profile = UserProfile(user_account = new_user, username = new_user.username, avatar = 'http://lorempixel.com/60/60/')
            new_profile.save()
            
            new_user_session = auth.authenticate(username = request_username, password = request_password)
            auth.login(request, new_user_session)
            
            return HttpResponseRedirect(request.GET.get('continue', 'http://localhost/'))
            
            
        return render(request, 'signup.html', {'page_title': 'Sign Up', 'errors': '0'})
Example #9
0
File: api.py Project: nrabe/todoapp
def api_signup(request, email=None, password=None, first_name=None, last_name=None):
    """
    registers a new user and authenticates it

    :param email:
    :param password:
    :param first_name:
    :param last_name:
    :return: :json:`{"profile": {"id": ""}, "sessionid": ""}`
    :raises ApiException: (200, 'Missing or invalid parameter FIELD_NAME VALUE')
    :raises ApiException: (402, 'Invalid email address or password')
    :raises ApiException: (403, 'Email address already registered')
    """

    email = param_email(email, required=True, blank=False, field_name='email')
    password = param_string(password, required=True, blank=False, field_name='password')
    first_name = param_string(first_name, required=False, blank=False, field_name='first_name')
    last_name = param_string(last_name, required=False, blank=False, field_name='last_name')

    UserProfile.create_user(
            email=email,
            password=password,
            first_name=first_name,
            last_name=last_name)
    response_json = _signin(request, email=email, password=password)

    curr_user = get_curr_user(request, required=True)
    emails.send_welcome_email(curr_user)

    return response_json
Example #10
0
    def authenticate(self, token=None, request=None):
        """ Reads in a Facebook code and asks Facebook if it's valid and what
        user it points to. """
        args = {
            'client_id': settings.FACEBOOK_APP_ID,
            'client_secret': settings.FACEBOOK_APP_SECRET,
            'redirect_uri': request.build_absolute_uri(
                                            reverse('facebook_callback')),
            'code': token,
        }

        # Get a legit access token
        target = urllib.urlopen(
                        'https://graph.facebook.com/oauth/access_token?'
                            + urllib.urlencode(args)).read()
        response = cgi.parse_qs(target)
        access_token = response['access_token'][-1]

        # Read the user's profile information
        fb_profile = urllib.urlopen(
                'https://graph.facebook.com/me?access_token=%s' % access_token)
        fb_profile = json.load(fb_profile)

        try:
            # Try and find existing user
            fb_user = UserProfile.objects.get(facebook_id=fb_profile['id'])
            user = fb_user.user
            # Update access_token
            fb_user.access_token = access_token
            fb_user.save()
        except UserProfile.DoesNotExist:
            # No existing user
            if getattr(settings, 'FACEBOOK_FORCE_SIGNUP', False):
                # No existing user, use anonymous
                user = AnonymousUser()
                user.username = username
                user.first_name = fb_profile['first_name']
                user.last_name = fb_profile['last_name']
                fb_user = UserProfile(
                        facebook_id=fb_profile['id'],
                        access_token=access_token
                )
                user.facebookprofile = fb_user
            else:
                # No existing user, create one
                user = User.objects.create_user(fb_profile['id'],
                                                fb_profile['email'])
                user.first_name = fb_profile['first_name']
                user.last_name = fb_profile['last_name']
                # with django-primate User has one field called 'name' instead
                # of first_name and last_name
                user.name = u'%s %s' % (user.first_name, user.last_name)
                user.save()

                # Create the UserProfile
                fb_user = UserProfile(user=user,
                                          facebook_id=fb_profile['id'],
                                          access_token=access_token)
                fb_user.save()
        return user
def add_offer(request):
    enterprise = Enterprise.objects.get(pk=request.user.id)
    error = None

    # If the enterprise has closed offers without feedback
    if enterprise.get_closed_offers_without_feedback():
        request.flash['error_message'] = 'No puede crear nuevas ofertas hasta entregar el feedback de las ya cerradas'
        return HttpResponseRedirect(reverse('bolsa_trabajo.views_enterprise.offer'))

    if request.method == 'POST':
        form = OfferForm(request.POST)
        if form.is_valid():
            offer = Offer.create_from_form(enterprise, form)
            offer.save()

            UserProfile.notify_staff_of_new_offer()

            request.flash['message'] = 'Oferta propuesta exitosamente, por favor espere a que un encargado la valide'
            url = reverse('bolsa_trabajo.views_account.index')
            return HttpResponseRedirect(url)
    else:
        form = OfferForm()

    return append_user_to_response(request, 'enterprise/add_offer.html', {
        'offer_form': form,
        'error': error
    })
Example #12
0
def _register(request):
    if REGISTER_TURN_OFF:
        return render('register_turn_off.html', RequestContext(request))
    if request.user.is_authenticated():
        auth.logout(request)
    if request.method == 'GET':
        form = RegisterForm()
        return render('register.html', RequestContext(request, {'form': form}))
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            data = form.clean()
            if data['password'] != data['re_password']:
                return render('register.html', RequestContext(request, {'form': form}))
            obj_user = User.objects
            if obj_user.filter(username=data['username']).exists() or obj_user.filter(email=data['email']).exists():
                messages.error(request, 'user or email already existed')
                return render('register.html', RequestContext(request, {'form': form}))
            new_user = obj_user.create_user(username=data['username'], password=data['password'], email=data['email'])
            new_user.is_active = True
            new_user.is_staff = True
            new_user.save()
            new_profile = UserProfile(user=new_user)
            try:
                new_profile.save()
                return HttpResponseRedirect('/')
            except:
                messages.error(request, 'register new user failed!')
                return render('register.html', RequestContext(request, {'form': form}))
            return HttpResponseRedirect('/')
        return render('register.html', RequestContext(request, {'form': form}))
Example #13
0
def _register(request):
    """
    用户注册
    """

    form = RegisterForm(request.POST)
    if form.is_valid():
        data = form.clean()
    else:
        return render('account_register.html',locals(),context_instance=RequestContext(request))

    # 检查email是否存在
    try:
        user = User.objects.get(username=data['username'])
    except User.DoesNotExist:
        pass
    else:
        messages.error(request,'email已经注册过,请换一个')
        return render('account_register.html',locals(),context_instance=RequestContext(request))

    # 创建新用户
    new_user = User.objects.create_user(username=data['username'],email=data['username'],
                                        password=data['password'])
    new_user.is_active = False
    new_user.save()
    new_profile = UserProfile(user=new_user,screen_name=data['screen_name'])

    try:
        new_profile.save()
        return HttpResponseRedirect('/accounts/active/%d/not_active/' %new_user.id)
    except Exception,e:
        messages.error(request,'服务器出现错误:%s' %e)
Example #14
0
def register(request):
    error = ''
    if request.method == 'GET':
        return render_to_response('usercenter_register.html',{},context_instance=RequestContext(request))
    else:
        username = request.POST['username'].strip()
        email = request.POST['email'].strip()
        password = request.POST['password'].strip()
        re_password = request.POST['re_password'].strip()

        if not username or not password or not email:
            error = u'任何字段都不能为空'
        if password != re_password:
            error = u'密码不一致'
        if User.objects.filter(username=username).count() > 0:
            error = u'用户已存在'
        if not error:
            user = User.objects.create_user(username=username,email=email,password=password)
            user.is_active = False
            user.save()
            profile = UserProfile(owner=user,avatar="http://res.myform.com/mmexport1445957752296.jpg")
            profile.save()

            new_code = str(uuid.uuid4()).replace("-","")
            expire_time = datetime.datetime.now() + datetime.timedelta(days=2)
            code_record = ActivateCode(owner=user,code=new_code,expire_timestamp=expire_time)
            code_record.save()

            activate_link = "http://%s%s" % ((request.get_host()),reverse("usercenter_activate",args=[new_code]))
            send_mail(u'激活邮件',u'您的激活链接为: %s' % activate_link,"*****@*****.**",[email],fail_silently=False)
        else:
            return render_to_response("usercenter_register.html",{"error":error},context_instance=RequestContext(request))
        return redirect('login')
Example #15
0
    def save(self, profile_callback=None):
        """
        Creates the new ``User`` and ``RegistrationProfile``, and
        returns the ``User``.

        Also create the userprofile with additional info from the form.

        Differs from the default by using the email address as the username.
        """

        # construct a username based on the email address
        # need to truncate to 30 chars
        username = self.cleaned_data['email'].replace('@', '').replace('.', '')
        username = username[:30]

        new_user = RegistrationProfile.objects.create_inactive_user(username=username,
                                                                    password=self.cleaned_data[
                                                                        'password1'],
                                                                    email=self.cleaned_data[
                                                                        'email'],
                                                                    firstname=self.cleaned_data[
                                                                        'firstname'],
                                                                    lastname=self.cleaned_data[
                                                                        'lastname'],
                                                                    profile_callback=profile_callback)

        # now also create the userprofile for this user with
        # the extra information from the form

        profile = UserProfile(user=new_user)

        profile.save()

        return new_user
Example #16
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'],
            password=self.cleaned_data['password1'],
            email=self.cleaned_data['email'],
            profile_callback=profile_callback)
        new_user.first_name = self.cleaned_data['first_name']
        new_user.last_name = self.cleaned_data['last_name']
        new_user.save()

        new_profile = UserProfile(
            user=new_user,
            fiscale_code=self.cleaned_data['codice_fiscale'],
            telephone=self.cleaned_data['telefono'],
            area=self.cleaned_data['area'],
            personal_data=self.cleaned_data['personal_data'],)
        new_profile.save()
        return new_user
Example #17
0
    def test_mine(self):

        user_info = {'username': '******',
                 'email': '[email protected]',
                 'password': '******'}

        new_user = User.objects.create_user(**user_info)
        user_profile = UserProfile()
        user_profile.user = new_user

        scan = ScanningEquipment.objects.get_or_create(name="Oil Lamp", modifier=0.2, image='icons/Scan/Oil Lamp.png', price=1, description="It won't allow you to see much but it's better than going in blind!", store_val=20)[0]
        dig = DiggingEquipment.objects.get_or_create(name='Spoon', modifier=0.3, time_modifier=5, image='icons/Tools/Spoon.png', price=1, description="What am I supposed to do with this?", store_val=30)[0]
        move = Vehicle.objects.get_or_create(name='Boots', modifier=10, image='icons/Vehicle/Boots.png', price=1, description="Two boots is better than no boots!")[0]
        user_profile.equipment = scan
        user_profile.tool = dig
        user_profile.vehicle = move

        accuracy = 0.2
        max_gold = 100
        gen = yieldgen.ScotlandQuadraticYieldGenerator(depth=10, max=max_gold, min=0)

        m = mine.Mine(gen, accuracy, user_profile)

        for block in m.blocks:
            self.failIf(block.cue == None)
            self.failIf(block.gold == None)
            self.failIf(block.dug == True)
            self.failIf((block.pos/10)>=1)
            self.failIf((block.pos/10)<=-1)
Example #18
0
    def test_user_profile_data(self):
        """
        Check if UserProfile object is created with appropriate  data
        """
        user_info = {'username': '******',
                 'email': '*****@*****.**',
                 'password': '******'}

        new_user = User.objects.create_user(**user_info)
        user_profile = UserProfile()
        user_profile.user = new_user

        scan = ScanningEquipment.objects.get_or_create(name="Oil Lamp", modifier=0.2, image='icons/Scan/Oil Lamp.png', price=1, description="It won't allow you to see much but it's better than going in blind!", store_val=20)[0]
        dig = DiggingEquipment.objects.get_or_create(name='Spoon', modifier=0.3, time_modifier=5, image='icons/Tools/Spoon.png', price=1, description="What am I supposed to do with this?", store_val=30)[0]
        move = Vehicle.objects.get_or_create(name='Boots', modifier=10, image='icons/Vehicle/Boots.png', price=1, description="Two boots is better than no boots!")[0]
        user_profile.equipment = scan
        user_profile.tool = dig
        user_profile.vehicle = move

        self.assertEqual(user_profile.user.username, 'guybrush')
        self.assertEqual(new_user.email, '*****@*****.**')
        self.failUnless(new_user.check_password('secret'))
        self.failIf(not new_user.is_active)
        self.failIf(not user_profile.equipment)
        self.failIf(not user_profile.tool)
        self.failIf(not user_profile.vehicle)
        self.assertEqual(user_profile.gold, 100)
        self.assertEqual(user_profile.games_played, 0)
        self.assertEqual(user_profile.game_overs, 0)
        self.assertEqual(user_profile.mines, 0)
Example #19
0
 def register(self, request, form_class):
     new_user = super(MyRegistrationView).register(self, request, form_class)
     user_profile = UserProfile()
     user_profile.user = new_user
     user_profile.field = form_class.cleaned_data['field']
     user_profile.save()
     return user_profile
Example #20
0
File: views.py Project: lngz/misj
def regist(request):

    if request.method == "POST":
        form = UserForm(request.POST)

        if form.is_valid():

            loginname = form.cleaned_data["loginname"]
            username = form.cleaned_data["username"]
            password = form.cleaned_data["password"]
            rule_no = form.cleaned_data["rule_no"]
            intro = form.cleaned_data["intro"]
            contact = form.cleaned_data["contact"]
            email = form.cleaned_data["email"]

            userid = User.objects.create_user(username=loginname, email=email, password=password)
            new_usr_profile = UserProfile(
                user=userid,
                loginname=loginname,
                username=username,
                password=password,
                rule_no=rule_no,
                intro=intro,
                contact=contact,
                email=email,
            )
            new_usr_profile.save()

            return HttpResponseRedirect("/")
    else:
        form = UserForm()

    return render_to_response("register.html", {"form": form})
Example #21
0
def account_login(request):
    # print request.method
    if request.method == 'GET':
        return render(request, 'one_finger/login.html')

    else:
        # print request.POST
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username,
                            password=password)
        if user is not None:
            print 'user_login ok'
            login(request, user)
            if not UserProfile.objects.filter():
                admin_obj = User.objects.first()
                user_obj = UserProfile(name=admin_obj.username,
                                       user_id=admin_obj.id)
                user_obj.save()
            user.userprofile.online = True
            user.userprofile.save()
            # check_cloud()
            status = check_cloud()
            # pdb.set_trace()
            if status:
                return HttpResponseRedirect('/')
            else:
                return HttpResponseRedirect('/input')
        else:
            return render(request, 'one_finger/login.html', {
                'login_err': "Wrong username or password!"
            })
Example #22
0
    def done(self, form_list, form_dict, **kwargs):
        with transaction.atomic():
            user_data = form_dict["user"].cleaned_data
            phone_number = user_data["country_code"] + user_data["phone_number"]
            email = user_data["email"]
            username = user_data["username"]

            user = form_dict["user"].save()

            salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
            activation_key = hashlib.sha1(salt + email).hexdigest()
            key_expires = timezone.now() + timedelta(days=30)

            user_profile = UserProfile(
                user=user, phone_number=phone_number, activation_key=activation_key, key_expires=key_expires
            )
            user_profile.save()

            email_subject = "Account Confirmation"
            confirmation_url = self.request.build_absolute_uri(
                reverse("email_confirm", kwargs={"activation_key": activation_key})
            )
            email_body = (
                "Hello %s, thanks for signing up. To activate your account,\
click this link %s"
                % (username, confirmation_url)
            )

            send_email.delay(email_subject, email_body, [email])
            messages.success(
                self.request,
                "You've successfully signed up. Please click the activation link sent to your email to activate your account",
            )
            return HttpResponseRedirect("/")
Example #23
0
File: views.py Project: 3241966/PMS
def login_user(request):
	url = request.GET.get('next','/')
	
	if url == reverse('accounts.views.create_account'):
		url = "/"

	if request.method == 'POST':
		form = LoginForm(request.POST)
		if form.is_valid():
			user = authenticate(username = form.cleaned_data['username'],password = form.cleaned_data['password'])
			
			if user:
				if user.is_active:
					try:
						user.get_profile()
					except UserProfile.DoesNotExist:
						profile = UserProfile(user=user)
						profile.save()
						
					login(request,user)
					return HttpResponseRedirect(url)
				else:
					messages.add_message(request,messages.WARNING,'Your account has been disabled')
					return HttpResponseRedirect("/")
			else:
				messages.add_message(request,messages.ERROR,'Username / password do not match')
		else:
			messages.add_message(request,messages.ERROR,'Username / password do not match')
		
	else:
		form = LoginForm()
		
	return render_to_response("login.html",{ 'form' : form,'next' : url },context_instance=RequestContext(request))
Example #24
0
    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        message = None

        if form.is_valid():
            cd = form.cleaned_data
            user = User()

            user.username = cd["username"]
            user.email = cd["email"]
            user.set_password(cd["password"])

            try:
                user.save()

                # create UserProfile
                profile = UserProfile()
                profile.user = user
                profile.save()
                return HttpResponseRedirect("/")
            except IntegrityError:
                message = "The username you entered is taken"

        return render(
            request, self.template_name, {"form": form, "message": message}, context_instance=RequestContext(request)
        )
Example #25
0
def my_account(request):
    if request.user:
        try:
            profile = UserProfile.objects.get(user=request.user)
        except:
            profile = UserProfile(user=request.user)
            profile.save()
Example #26
0
def register(request):
	if request.user.is_authenticated():
		return HttpResponseRedirect(reverse("home"))
	else:
		if request.method == 'POST':
			form = RegisterForm(request.POST)
			
			x_user = User.objects.filter(email=request.POST["email"])
			if x_user.count() > 0:
				form.add_error('email', _('Este email ya existe'))
			else:
				if form.is_valid():
					current = form.save(commit=False)
					current.save()
					perfil = UserProfile()
					perfil.user = current
					perfil.save() 


					complete_signup(request, current,app_settings.EMAIL_VERIFICATION, "/")
					return HttpResponseRedirect(reverse("registered"))


		else:
			form = RegisterForm()
		return render(
			request, 
			'register.html',
				{
					"form": form
				}
			)
Example #27
0
def passet(request):
    """ Set credentials for new users registered with social auth. """
    ctx = {
        'title': _("Set your password"),
    }
    if request.method == 'POST':
        f = SocialAuthPassetForm(request.POST)
        if f.is_valid():
            user = User(request.user.id)
            user.username = f.cleaned_data['username']
            user.set_password(f.cleaned_data['password'])
            # Re-fetch user object from DB
            user = User.objects.get(pk=request.user.id)
            # Create user profile if not exists
            try:
                prof = UserProfile.objects.get(user=request.user.id)
            except:
                prof = UserProfile()
                prof.user = user
                prof.save()
            return redirect('user:index')
        ctx['form'] = SocialAuthPassetForm(request.POST)
        return render(request, 'userspace/pass.html', ctx)
    ctx['form'] = SocialAuthPassetForm()
    return render(request, 'userspace/pass.html', ctx)
Example #28
0
def register_account(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect("index")

    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        profile_form = forms.ProfileForm(request.POST)
        if form.is_valid() and profile_form.is_valid():
            user = form.save()

            profile = UserProfile()
            profile.user = user
            profile_form = forms.ProfileForm(request.POST, instance=profile)
            profile_form.save()

            user = authenticate(username=request.POST['username'],
                         password=request.POST['password1'])
            login(request, user)
            return HttpResponseRedirect("index")
    else:
        form = UserCreationForm()
        profile_form = forms.ProfileForm()

    return render_to_response("registration/account.html", RequestContext(request,
        {
            'form' : form,
            'profile_form' : profile_form,
        }))
Example #29
0
 def setUp(self):
     user = User.objects.create_user(username='******', password='******')
     user_profile = UserProfile()
     user_profile.user_id = user.id
     user_profile.phone = '111'
     user_profile.save()
     user = User.objects.create_user(username='******', password='******')
Example #30
0
def register(request):
    if request.method == 'POST':
        rf = RegisterForm(request.POST)

        if rf.is_valid():
            data = rf.clean()
        else:
            return render('regist.html',locals(),context_instance=RequestContext(request))

        try:
            user = User.objects.get(username=data['username'])
        except User.DoesNotExist:
            pass
        else:
            messages.error(request,'email已经注册过,请换一个')
            return render('regist.html',locals(),context_instance=RequestContext(request))

        new_user = User.objects.create_user(username=data['username'],email=data['username'],password=data['password'])
        new_user.save()
        new_profile = UserProfile(user=new_user,screen_name=data['screen_name'])

        new_profile.save()

        return HttpResponseRedirect('/account/login/')

    else:
        rf = RegisterForm()
    return render('regist.html',locals(),context_instance=RequestContext(request))
Example #31
0
        # 设置一个默认的密码,当然,这个密码是没用的,不可以通过输入用户名和密码来登陆
        new_user = User.objects.create_user(username=username,email='*****@*****.**',password=settings.DEFAULT_PASSWORD)
        new_user.is_active = True
        try:
            new_user.save()
        except Exception,e:
            return HttpResponse('连接新浪账号时出错:%s'%e)
        
        # 获取用户的新浪账号
        try:
            sina_profile = client.get.users__show(uid=uid)
        except Exception,e:
            raise ValueError(e)

        # 增加用户档案
        new_prfile = UserProfile(user=new_user)
        new_prfile.screen_name = sina_profile['screen_name'][:10] # 截取前10个字符
        new_prfile.city = '北京'
        new_prfile.introduction = sina_profile['description'][:150]

        # 设置链接信息
        try:
            weibo = Link(user=request.user,type='weibo')
            weibo.name = sina_profile['screen_name']
            weibo.url = 'http://weibo.com/' + sina_profile['profile_url']  
            weibo.save()
        except:
            pass

        try:
            new_prfile.save()
Example #32
0
    def test_delete(self):
        UserProfile.get_one(guid=self.users[0].guid).delete()
        db.session.commit()

        assert UserProfile.get_one(guid=self.users[0].guid) is None
Example #33
0
def create_profile(sender, **kw):
    user = kw["instance"]
    if kw["created"]:
        profile = UserProfile(user=user)
        profile.save()
Example #34
0
    def post(self, request, *args, **kwargs):
        if self.request.user.is_authenticated() == True:
            #userProf = self.request.user
            userProf = UserProfile.objects.filter(
                username=self.request.user.username)[0]
        else:
            userProf = UserProfile()
            userProf.username = request.POST['username']
            userProf.reg_ip = request.META['REMOTE_ADDR']
            userProf.login_ip = request.META['REMOTE_ADDR']

        if (request.POST['password'] != "") & (request.POST['password']
                                               == request.POST['password2']):
            userProf.set_password(request.POST['password'])
        userProf.nickname = request.POST['nickname']
        userProf.email = request.POST['email']
        userProf.school = request.POST['school']
        userProf.stu_no = request.POST['stu_no']
        userProf.realname = request.POST['realname']
        userProf.birthday = request.POST['birthday']
        userProf.address = request.POST['address']
        userProf.phone = request.POST['phone']
        userProf.department = request.POST['department']
        userProf.institute = request.POST['institute']
        if request.POST['sex'] == 'male':
            userProf.gender = 1
        else:
            userProf.gender = 0
        userProf.save()
        return HttpResponseRedirect('/')
Example #35
0
def create_profile(request,
                   form_class=None,
                   success_url=None,
                   template_name='profiles/create_profile.html'):
    """
    Create a profile for the user, if one doesn't already exist.
    Borrowed from django-profile.
    
    If the user already has a profile, as determined by
    ``request.user.get_profile()``, a redirect will be issued to the
    :view:`profiles.views.edit_profile` view. If no profile model has
    been specified in the ``AUTH_PROFILE_MODULE`` setting,
    ``django.contrib.auth.models.SiteProfileNotAvailable`` will be
    raised.
    
    To specify the form class used for profile creation, pass it as
    the keyword argument ``form_class``; if this is not supplied, it
    will fall back to ``form_for_model`` for the model specified in
    the ``AUTH_PROFILE_MODULE`` setting.
    
    If you are supplying your own form class, it must define a method
    named ``save()`` which corresponds to the signature of ``save()``
    on ``form_for_model``, because this view will call it with
    ``commit=False`` and then fill in the relationship to the user
    (which must be via a field on the profile model named ``user``, a
    requirement already imposed by ``User.get_profile()``) before
    finally saving the profile object. If many-to-many relations are
    involved, the convention established by ``form_for_model`` of
    looking for a ``save_m2m()`` method on the form is used, and so
    your form class should define this method.
    
    To specify a URL to redirect to after successful profile creation,
    pass it as the keyword argument ``success_url``; this will default
    to the URL of the :view:`profiles.views.profile_detail` view for
    the new profile if unspecified.
    
    To specify the template to use, pass it as the keyword argument
    ``template_name``; this will default to
    :template:`profiles/create_profile.html` if unspecified.
    
    Context:
    
        form
            The profile-creation form.
    
    Template:
    
        ``template_name`` keyword argument, or
        :template:`profiles/create_profile.html`.
    
    """
    try:
        profile_obj = request.user.get_profile()
        return HttpResponseRedirect(reverse('profiles_edit_profile'))
    except ObjectDoesNotExist:
        pass
    profile_model = get_profile_model()
    if success_url is None:
        success_url = reverse('profiles_profile_detail',
                              kwargs={'username': request.user.username})
    if form_class is None:
        form_class = ProfileForm
        initial = {'user': request.user, 'email': request.user.email}
    if request.method == 'POST':
        form = form_class(request.user, request.POST)
        if form.is_valid():
            profile_obj = UserProfile()
            profile_obj = form.save(commit=False)
            profile_obj.user = request.user
            profile_obj.save()
            if hasattr(form, 'save_m2m'):
                form.save_m2m()
            return HttpResponseRedirect(success_url)
    else:
        form = form_class(request.user, initial=initial)
    return render_to_response(template_name, {'form': form},
                              context_instance=RequestContext(request))
Example #36
0
def dashboard(request):
    '''
    The dashboard view function
    '''
    profile = UserProfile.get_or_create_profile(request.user)

    if (not profile.is_net_admin):
        next_steps = 0
        opts = []
        ufs = UserFlowSpace.objects.filter(user=request.user)
        if (len(ufs) == 0):
            rufs = RequestedUserFlowSpace.objects.filter(user=request.user)
            if (len(rufs) == 0):
                next_steps = 0
            else:
                next_steps = 1
        else:
            opts = UserOpts.objects.filter(
                user=request.user).order_by('-priority')
            if (len(opts) == 0):
                next_steps = 2
            else:
                next_steps = 3

        return simple.direct_to_template(
            request,
            template='openflow/optin_manager/dashboard_user.html',
            extra_context={
                'user': request.user,
                'next_steps': next_steps,
                'opts': opts,
            },
        )
    else:  #Admin
        adminfs = AdminFlowSpace.objects.filter(user=request.user)

        opts = UserOpts.objects.filter(user=request.user).order_by('-priority')
        optsfs = []
        for opt in opts:
            fses = opt.optsflowspace_set.all()
            for fs in fses:
                optsfs.append(fs)

        num_user_reqs = RequestedUserFlowSpace.objects.filter(
            admin=request.user).count()
        num_admin_reqs = RequestedAdminFlowSpace.objects.filter(
            admin=request.user).count()
        num_admin_promotes = AdminPromoteRequest.objects.filter(
            admin=request.user).count()
        return simple.direct_to_template(
            request,
            template='openflow/optin_manager/dashboard_admin.html',
            extra_context={
                'user': request.user,
                'optsfs': optsfs,
                'adminfs': adminfs,
                'num_admin_reqs': num_admin_reqs,
                'num_user_reqs': num_user_reqs,
                'num_admin_promotes': num_admin_promotes,
            },
        )
Example #37
0
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg'}
server_path = app.config['SERVER_PATH']


@pytest.mark.parametrize("test_authorized_username, test_username, expected_output",

                         [
                             ('khaled', 'omar', UserProfile({"username": "******",
                                                             "screen_name": "3moar",
                                                             "bio": "he is a late man",
                                                             "birth_date": date(1998, 3, 23),
                                                             "created_at": datetime(2001, 12, 19, 10, 10, 24),
                                                             "followers_count": 1,
                                                             "following_count": 2,
                                                             "kweeks_count": 1,
                                                             "likes_count": 1,
                                                             "profile_banner_url": "server/banne.png"
                                                                                   "?11111111111111111111",
                                                             "profile_image_url": "server/profil.jpg"
                                                                                  "?11111111111111111111",
                                                             "following": False,
                                                             "follows_you": True,
                                                             "blocked": False,
                                                             "muted": False
                                                             })),
                             ('khaled', 'amr', UserProfile({"username": "******",
                                                            "screen_name": "bogy",
                                                            "bio": "he is a doll",
                                                            "birth_date": date(1998, 3, 23),
                                                            "created_at": datetime(2006, 12, 19, 10, 10, 24),
                                                            "followers_count": 1,
                                                            "following_count": 2,
Example #38
0
    def test_o2o_cross_database_protection(self):
        "Operations that involve sharing FK objects across databases raise an error"
        # Create a user and profile on the default database
        alice = User.objects.db_manager('default').create_user('alice', '*****@*****.**')

        # Create a user and profile on the other database
        bob = User.objects.db_manager('other').create_user('bob', '*****@*****.**')

        # Set a one-to-one relation with an object from a different database
        alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate')
        try:
            bob.userprofile = alice_profile
            self.fail("Shouldn't be able to assign across databases")
        except ValueError:
            pass

        # BUT! if you assign a FK object when the base object hasn't
        # been saved yet, you implicitly assign the database for the
        # base object.
        bob_profile = UserProfile.objects.using('other').create(user=bob, flavor='crunchy frog')

        new_bob_profile = UserProfile(flavor="spring surprise")
        new_bob_profile.save(using='other')

        charlie = User(username='******',email='*****@*****.**')
        charlie.set_unusable_password()
        charlie.save(using='other')

        # old object comes from 'other', so the new object is set to use 'other'...
        new_bob_profile.user = bob
        charlie.userprofile = bob_profile
        self.assertEqual(new_bob_profile._state.db, 'other')
        self.assertEqual(charlie._state.db, 'other')

        # When saved (no using required), new objects goes to 'other'
        bob_profile.save()
        self.assertEqual(list(User.objects.using('default').values_list('username',flat=True)),
                          [u'alice'])
        self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)),
                          [u'bob', u'charlie'])
        self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
                           [u'chocolate'])
        self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
                           [u'crunchy frog', u'spring surprise'])

        # This also works if you assign the O2O relation in the constructor
        denise = User.objects.db_manager('other').create_user('denise','*****@*****.**')
        denise_profile = UserProfile(flavor="tofu", user=denise)

        self.assertEqual(denise_profile._state.db, 'other')
        # ... but it isn't saved yet
        self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
                           [u'chocolate'])
        self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
                           [u'crunchy frog', u'spring surprise'])

        # When saved, the new profile goes to 'other'
        denise_profile.save()
        self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)),
                           [u'chocolate'])
        self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor',flat=True)),
                           [u'crunchy frog', u'spring surprise', u'tofu'])
Example #39
0
def get_user_profile(email):
    p = UserProfile.query(UserProfile.email == email)
    results = p.fetch(1)
    for profile in results:
        return profile
    return None
Example #40
0
 def testAnyUserBelongsToAllGroup(self):
     groups = UserProfile.for_user(self.user2).get_all_groups()
     self.assertEqual(groups, ['all'])