Esempio n. 1
0
def user_reg(request):
	username = request.POST.get('username')
	email = request.POST.get('email')
	password = request.POST.get('password')
	name = request.POST.get('student_name')
	gender = request.POST.get('gender')
	registerTime = datetime.now()
	if not (username and email and password):
		return HttpResponse(json.dumps({"error_code": "Can not be empty!", }), status=400)
	
	try:
		upr = User.objects.get(username=username)	#check if there is duplicated username
	except User.DoesNotExist:
		upr = None
	if upr is not None:
		return HttpResponse(json.dumps({"error": "用户名已被占用", }))

	try:
		upr = User.objects.get(email=email)		#check if there is duplicated email
	except User.DoesNotExist:
		upr = None
	if upr is not None:	
		return HttpResponse(json.dumps({"error": "Email已被使用", }))

	try:
		validate_email(email)
	except ValidationError:
		return HttpResponse(json.dumps({"error": "Email格式不正确", }))
	
	upr = User.objects.create_user(username, email, password)
	pr = Profile(user=upr, name=name, gender=gender, registerTime=registerTime)
	pr.save()

	return HttpResponse(json.dumps({"id": upr.id, }))
Esempio n. 2
0
 def create(self, validated_data):
     user = Profile(**validated_data)
     user.set_password(validated_data['password'])
     user.save()
     # FIXME
     self.fields.pop('password')
     return user
Esempio n. 3
0
def create_team(request, username):
    """
    Display the TeamCreationForm
    """
    if request.method == 'POST':
        form = TeamCreationForm(request.POST)
        if form.is_valid() and request.user.pk == form.cleaned_data['creator']:
            team = User.objects.create_user(form.cleaned_data['name'])
            team_creator_attrs = dict(
                team=team, 
                user=request.user, 
                permission=4, 
                creator=True
            )
            team_creator = TeamMember(**team_creator_attrs)
            team_creator.save()
            try:
                profile = team.get_profile()
            except Profile.DoesNotExist:
                profile = Profile(user=team)
            profile.organization = True
            profile.creator_id = request.user.pk
            profile.save()
            HttpResponseRedirect(reverse('update_team', args=(form.cleaned_data["name"],)))
    else:
        form = TeamCreationForm(initial={'creator': request.user.pk})
    return render_to_response('teams/team_create.html', 
        {'form': form, 'username': username},
        context_instance=RequestContext(request))
Esempio n. 4
0
    def test_profile(self):
        from profiles.models import Profile
        p = Profile()
        self.assertEqual(len(p.my_packages()), 0)

        r = MockGithubRepo()
        self.assertEqual(p.url_for_repo(r), None)
Esempio n. 5
0
def get_profile(user):
    try:
        return Profile.all().filter("user = ", user)[0]
    except IndexError:
        profile = Profile(user=user, notification=5)
        profile.save()
        return profile
    def handle_label(self, username, **options):
        from django.contrib.auth.models import User
        from profiles.models import Profile

        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'username': username}

        try:
            profile = Profile.objects.get(**kwargs)
        except Profile.DoesNotExist:
            try:
                user = User.objects.get(**kwargs)
            except User.DoesNotExist:
                raise CommandError("User '%s' does not exist" % username)

            print "Adding profile for %s" % username
            initial = dict([(f.name, getattr(user, f.name)) for f in user._meta.fields])
            profile = Profile(user_ptr=user, **initial)
            profile.save()
            for f in user._meta.many_to_many:
                getattr(profile, f.name).add(*getattr(user, f.name).all())

        else:
            raise CommandError("Profile '%s' already exists" % username)
Esempio n. 7
0
File: fake.py Progetto: braskin/pd
def create_profile(user, gender=None, lname=None):

    if gender is None:
        gender = get_random_gender()


    fname = get_random_fname(gender)

    if lname is None:
        lname = get_random_lname()

    zc = get_random_zip()
    photo = adult_photo(gender)

    profile = Profile()        
    profile.user = user
    profile.first_name = fname
    profile.last_name = lname
    profile.zip_code = zc
    profile.gender = gender

    profile.save()

    f = open(photo, 'r')
    np = Photo(album=profile.album, caption="Profile", original_image=File(f))
    np.save()

    profile.set_profile_pic(np)

    return profile 
Esempio n. 8
0
def User_Profile_Registration(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = RegistrationForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['profile_pic'])
            user = User.objects.create_user(username=form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password'])
            user.first_name = form.cleaned_data['first_name']
            user.last_name=form.cleaned_data['last_name']
            user.save()
            profile = Profile(user = user, countries=form.cleaned_data['countries'], about_me = form.cleaned_data['about_me'], birth_date = form.cleaned_data['birth_date'])
            profile.profile_pic=form.cleaned_data['profile_pic']
            profile.save()
            registredUser = authenticate(username = form.cleaned_data['username'], password= form.cleaned_data['password'])
            if registredUser is not None:
                login(request, registredUser)
                return HttpResponseRedirect('/')

            else:
                return HttpResponseRedirect('/registered')
    else:
        form = RegistrationForm()
        context = { 'form' : form }
        return render_to_response('register.html', context, context_instance=RequestContext(request))
    return HttpResponseRedirect('/')
Esempio n. 9
0
	def handle(self, *args, **options):
		for u in User.objects.all():
			p = Profile()
			p.member = u
			p.save()

			self.stdout.write('Profiles synced!')
Esempio n. 10
0
 def save(self, user):
     user.first_name = self.cleaned_data['first_name']
     user.last_name = self.cleaned_data['last_name']
     user.email= self.cleaned_data['email'] 
     user.username=user.email
     profile= Profile(first_name=user.first_name, last_name=user.last_name, is_student=self.cleaned_data["is_student"], email=user.email, username=user.username)
     profile.save()
     user.save()
Esempio n. 11
0
 def test_add_user(self):
     user = AppUser(user=User(email="*****@*****.**"),
                    username="******",
                    email="*****@*****.**",
                    is_staff=True).save()
     assert not Profile.all().count()
     profile = get_profile(user)
     assert profile.notification == 5
     assert Profile.all().count()
Esempio n. 12
0
def create_default_profile(app, created_models, verbosity, **kwargs):

    try:
        user = User.objects.get(id=1)
    except User.DoesNotExist:
        user = User(id=1, username="******", email=settings.DEFAULT_FROM_EMAIL)
        user.save()
        profile = Profile(user=user, first_name="Notification")
        profile.save()
Esempio n. 13
0
def register(request):
    ''' Registration for new users and new profiles '''
    # if the user is already logged in, send them to their profile 
    if request.user.is_authenticated():
        return HttpResponseRedirect('/profile/')
    # form was submitted 
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = User.objects.create_user(username=username,password=password)
            user.save()
            age = form.cleaned_data['age']
            zipcode = form.cleaned_data['zipcode']
            state = form.cleaned_data['state']
            gender = form.cleaned_data['gender']
            one_k = form.cleaned_data['one_k']
            five_k = form.cleaned_data['five_k']
            ten_k = form.cleaned_data['ten_k']
            one_mile = form.cleaned_data['one_mile']
            five_mile = form.cleaned_data['five_mile']
            ten_mile = form.cleaned_data['ten_mile']
            half_marathon = form.cleaned_data['half_marathon']
            full_marathon = form.cleaned_data['full_marathon']
            ultra_marathon = form.cleaned_data['ultra_marathon']
            trail_run = form.cleaned_data['trail_run']
            cross_country = form.cleaned_data['cross_country']
            short_distance = form.cleaned_data['short_distance']
            long_distance = form.cleaned_data['long_distance']
            competitive = form.cleaned_data['competitive']
            profile = Profile(
                user=user, age=age,zipcode=zipcode,state=state,
                gender=gender,one_k=one_k,five_k=five_k,
                ten_k=ten_k,one_mile=one_mile,five_mile=five_mile,
                ten_mile=ten_mile,half_marathon=half_marathon,
                full_marathon=full_marathon,ultra_marathon=ultra_marathon,
                trail_run=trail_run,cross_country=cross_country,
                short_distance=short_distance,long_distance=long_distance,
                competitive=competitive)
            profile.save()
            user = authenticate(username=username,password=password)
            auth_login(request,user)
            return HttpResponseRedirect('/profile/')
        # form was not valid
        else:
            context = {'form': form}
            return render(request,'profiles/register.html', context)
    # user is not submitting the form
    else:      
        form = RegistrationForm()
        context = { 'form': form }
        return render(request,'profiles/register.html', context)
Esempio n. 14
0
    def form_valid(self, form):
        """Form Valid

        If form valid User save in database with his profile.
        Generate Activation key with expire date.
        For User's email sended confirmation letter

        Return:
            Redirect

        """
        form.save()

        user_email = form.cleaned_data['email']

        activation_key = self.generate_activation_key(user_email)
        key_expires = self.generate_key_expires(settings.KEY_EXPIRE_TERM)

        user = User.objects.get(email=user_email)
        user.groups.add(Group.objects.get(name='customers'))

        slug = self.create_slug(user)

        new_profile = Profile(
            user=user,
            activation_key=activation_key,
            key_expires=key_expires,
            slug=slug
        )
        new_profile.save()

        email_data = {
            'username': user.username,
            'activation_key': activation_key
        }

        email = SendEmailClass(
            subject=_('Account Confirmation'),
            sender=settings.EMAIL_HOST_USER,
            to=settings.EMAIL_SUPERUSERS,
            template=settings.EMAIL_TEMPLATES['confirmation'],
            data=email_data
        )
        email.send()

        return render(
            self.request,
            settings.REGISTRATION_TEMPLATES['thanks'],
            context={
                'username': user.username,
                'email': user.email
            }
        )
Esempio n. 15
0
def get_profile(request):
    user = request.user
    if user.is_authenticated():
        try:
            profile = user.get_profile()
        except Profile.DoesNotExist:
            profile = Profile(user=user, name=user.username)
            profile.save()
    else:
        profile = "Anonymous"

    return {"profile": profile}
Esempio n. 16
0
 def create(self, email, password=None, *args, **kwargs):
     """
     Creates and saves a User with the given email, date of
     birth and password.
     """
     user = self.model(email=email, **kwargs)
     user.set_password(password)
     user.save()
     profile = Profile(
         user=user,
     )
     profile.save()
     return user
Esempio n. 17
0
 def create_membership(self, team, char_name, active=True):
     #print(team,char_name)
     try:
         return TeamMembership.objects.get(team=team, char_name__iexact=char_name), False
     except TeamMembership.DoesNotExist:
         if active:
             profile, created = Profile(name=char_name, user=self.master_user), True  # have to use fake name since admin doesn't have names
             profile.save()
             membership = TeamMembership(team=team, profile=profile, char_name=char_name)
             print("Creating player {0}".format(membership.char_name), file=self.stdout)
             membership.save()
             return membership, created
     return None, False
Esempio n. 18
0
    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)

        if commit:
            user.backend='django.contrib.auth.backends.ModelBackend'
            user.save()
            
            user_profile = Profile()
            user_profile.user = user
            user_profile.phone = self.cleaned_data["phone"]
            user_profile.save()
        
        return user
Esempio n. 19
0
def register_complete(request, id_booster, key):
    user = authenticate(username=id_booster, password=key)
    if not user:
        raise Http404

    if request.method == "POST":
        form = ProfileCoreForm(request.POST)
        if form.is_valid():
            # User
            user.first_name = form.cleaned_data["first_name"].lower().title()
            user.last_name = form.cleaned_data["last_name"].upper()
            user.set_password(form.cleaned_data["password"])
            user.is_active = True
            user.save()

            # create corresponding profile
            profile = Profile()
            profile.user_id = user.id
            profile.id_booster = user.username
            profile.promotion = form.cleaned_data["promotion"]
            profile.set_last_name(user.last_name)
            profile.save()

            # log & redirect
            user_auth = authenticate(username=user.username, password=form.cleaned_data["password"])
            login(request, user_auth)

            return redirect("accounts-register-rules")
    else:
        form = ProfileCoreForm()

    context = {"form": form, "pending_user": user}
    return direct_to_template(request, "accounts/register_complete.html", extra_context=context)
Esempio n. 20
0
def SignUp(request):
    if request.POST:
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            perfil = Profile(usuario=user)
            perfil.save()
            return HttpResponseRedirect('/Login/')
        else:
            return render_to_response('profiles/signUp.html',{'form':form}, context_instance=RequestContext(request))
    if request.user.is_authenticated():
        return HttpResponseRedirect('/Now/')
    else:
        form = SignUpForm()
    return render_to_response('profiles/signUp.html',{'form':form}, context_instance=RequestContext(request))
Esempio n. 21
0
    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)


        if commit:
            user.backend='django.contrib.auth.backends.ModelBackend'
            user.save()
            user_profile = Profile()
            user_profile.user = user
            user_profile.save()


            department = Department.objects.get(department_Name=self.cleaned_data['department_name'])
            department.department_Members.add(user)
        
        return user
Esempio n. 22
0
def login_page(request):
    try:
        if request.user.is_authenticated:
            return redirect("profile")

        data = {}
        if request.method == "POST":
            email = request.POST.get("email")
            password = request.POST.get("password")
            if not email or not password:
                return render(
                    request,
                    "profiles/login.html",
                    {"error": "Please fill email and password fields"},
                )

            user = User.objects.get(email=email)
            user = authenticate(username=user.username, password=password)
            if user is not None:
                login(request, user)
                return redirect("profile")

            data = {
                "error": "Invalid credentials, please check your email and password"
            }
    except User.DoesNotExist:
        client.captureException()

        email = request.POST.get("email")
        password = request.POST.get("password")
        username = email.split("@")[0]

        user = User.objects.create_user(
            email=email, username=username, password=password
        )
        profile = Profile(user=user)
        profile.save()

        user = authenticate(username=username, password=password)
        login(request, user)
        return redirect("profile")
    except Exception as e:
        client.captureException()
        logger.error(e)
        raise Http404

    return render(request, "profiles/login.html", data)
Esempio n. 23
0
def register(request):
    '''
    TO DO:
    Authenticate email
    '''
    if request.method == 'POST':
        formUser = UserForm(data=request.POST)
        formProfile=ProfileForm(data=request.POST)
        if formUser.is_valid() and formProfile.is_valid():
            password1=formUser.cleaned_data['password']
            password2=request.POST.get('password2')
            first_name=formUser.cleaned_data['first_name']
            last_name=formUser.cleaned_data['last_name']
            email=formUser.cleaned_data['email']
            if(password1!=password2):
                return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile,'passwordError':'passwordError'})
            if User.objects.filter(username = email).exists():
                return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile, 'error_message':'error_message'})
            user = formUser.save()
            user.set_password(user.password)
            user.is_active = False
            user.first_name=first_name
            user.last_name=last_name
            user.email=email
            user.username=email
    
            body=formProfile.cleaned_data['body']
            birthDate=formProfile.cleaned_data['birthDate']
            gender=formProfile.cleaned_data['gender']
            city=formProfile.cleaned_data['city']
            country=formProfile.cleaned_data['country']
            address=formProfile.cleaned_data['address']
            postalCode=formProfile.cleaned_data['postalCode']
            phoneNumber=formProfile.cleaned_data['phoneNumber']
            try:
                image = request.FILES['image']
            except:
                image=""
            user.save()
            newProfile=Profile(user=user,body=body,birthDate=birthDate,gender=gender,city=city,address=address,postalCode=postalCode,phoneNumber=phoneNumber,country=country,image=image)
            newProfile.save()
            return HttpResponseRedirect('/profiles/login')
    else:
        formUser = UserForm()
        formProfile=ProfileForm()
    return render(request, 'register.html', {'formUser': formUser, 'formProfile':formProfile})
Esempio n. 24
0
File: forms.py Progetto: braskin/pd
 def create_profile(self, user=None, profile_data=None, commit=True):
     profile = Profile()
     if user is None:
         raise NotImplementedError("SignupForm.create_profile requires a valid user")
         
     profile.user = user
     profile.first_name = profile_data["first_name"]
     profile.last_name = profile_data["last_name"]
     profile.zip_code = profile_data["zip_code"]
     profile.gender = profile_data["gender"]
     profile.source = profile_data["source"]
     
     profile.save()
     
     return profile 
Esempio n. 25
0
    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)

        form = UserCreationForm(request.POST)

        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            
            profile = Profile(user=user)
            profile.save()

            login(request, user)
            return redirect(request.POST.get('next','/'))
            
        context['form'] = form
        return self.render_to_response(context)
Esempio n. 26
0
def register(request):
	u = User()
	c = PostCount()
	p = Profile()
	if request.method == "POST":
		u.username = request.POST.get('user')
		u.set_password(request.POST.get('pass'))
		u.email = request.POST.get('email')
		u.is_active = True
		u.is_staff = False
		u.is_superuser = False
		u.save()
		c.user = u
		c.count = 0
		c.save()
		p.member = u
		p.save()
		return HttpResponseRedirect('/login/')
	return render(request, 'auth/register.html')
Esempio n. 27
0
 def after_signup(self, request, user, emailAddress, **kwargs):
     profile = None
     
     try:
         profile = Profile.objects.get(user=user)
     except Profile.DoesNotExist:
         profile = Profile(user=user)
     
     profile.name = self.cleaned_data.get("nickname")
     #profile.city = City.objects.getById(id=2)  #TODO, load from cities cache
     profile.save()
     
     #=======================================================
     #code in the bookstore
     '''为注册用户创建购物车'''
     try:
         cart = Cart.objects.get(owner=profile)
     except Cart.DoesNotExist:
         cart = Cart(owner=profile)
     
     cart.save()
Esempio n. 28
0
def thanks(request, redirect_url=settings.LOGIN_REDIRECT_URL):

    # Now that we've got the magic tokens back from Twitter, we need to exchange
    # for permanent ones and store them...
    oauth_token = request.session['request_token']['oauth_token']
    oauth_token_secret = request.session['request_token']['oauth_token_secret']
    twitter = Twython(settings.TWITTER_KEY, settings.TWITTER_SECRET,
                      oauth_token, oauth_token_secret)

    # Retrieve the tokens we want...
    authorized_tokens = twitter.get_authorized_tokens(request.GET['oauth_verifier'])

    # If they already exist, grab them, login and redirect to a page displaying stuff.
    try:
        user = User.objects.get(username=authorized_tokens['screen_name'])

    except User.DoesNotExist:

        # We mock a creation here; no email, password is just the token, etc.
        user = User.objects.create_user(authorized_tokens['screen_name'], "*****@*****.**", authorized_tokens['oauth_token_secret'])
        profile = Profile()
        profile.user = user
        profile.oauth_token = authorized_tokens['oauth_token']
        profile.oauth_secret = authorized_tokens['oauth_token_secret']
        profile.save()


    user = authenticate(
        username=authorized_tokens['screen_name'],
        password=authorized_tokens['oauth_token_secret']
    )
    login(request, user)
    redirect_url = request.session.get('next_url', redirect_url)

    return HttpResponseRedirect("/")
def home(request):
	user = request.user.username
	user_exists = Profile.objects.filter(username=user)
	user_profile = Profile.objects.filter(username=user, completed=False)
	
	# Verify if New User
	if user_exists.count() < 1:
		profile = Profile(username=user)
		user_prefs = FilterPreference(username=user)
		profile.save()
		user_prefs.save()
		
		return HttpResponseRedirect('/swt/profiles/new/')
	# Verify if Incomplete User Profile
	elif user_profile.count() > 0:
		return HttpResponseRedirect('/swt/profiles/new/')
	else:
		profile = Profile.objects.get(username=user)    
  
	args = {}
	args.update(csrf(request))
	args['profile'] = profile

    # WORKOUTS ARGUMENTS
	args['workouts'] = Workout.objects.filter(username=user).order_by('-date')[0:5]

    # FRIENDLIST ARGUMENTS
	args['friends_accepted'] = FriendList.objects.filter(sender_id=user, accepted=True).order_by('receiver_id')
	args['friends_pending'] = FriendList.objects.filter(sender_id=user, accepted=False)
	args['friends_request'] = FriendList.objects.filter(receiver_id=user, accepted=False)
	args['friends_form'] = FriendsForm()
	
	# GYMSTATUS ARGUMENTS
	args['gym_status'] = GymStatus.objects.all()
	
	args['curr_weekday'] = strftime("%A")
	args['curr_hour'] = strftime("%H")
	

	return render_to_response('home-index.html', args)
Esempio n. 30
0
def _register(request):
	if request.POST:
		username = request.POST.get('username')
		email = request.POST.get('email')
		password = request.POST.get('password')
		name = request.POST.get('name')
		gender = 0
		if request.POST.get('gender') == "1":
			gender = 1
		elif request.POST.get('gender') == "2":
			gender = 2
		registerTime = datetime.now()
	else:
		return HttpResponseRedirect(reverse('index'))

	try:
		upr = User.objects.get(username=username)	#check if there is duplicated username
	except User.DoesNotExist:
		upr = None
	if upr is not None:
		return __goErrorPage(request, ["duplicated username", ])

	try:
		upr = User.objects.get(email=email)		#check if there is duplicated email
	except User.DoesNotExist:
		upr = None
	if upr is not None:	
		return __goErrorPage(request, ["dupicated email!", ])
	
	form = {}
	if __judge_form(form):
		upr = User.objects.create_user(username, email, password)
		pr = Profile(user=upr, name=name, gender=gender, registerTime=registerTime)
		pr.save()
		userpr = authenticate(username=username, password=password)
		login(request, userpr)
	else:
		return __goErrorPage(request, ["something wrong with your form", ])
	
	return HttpResponseRedirect(reverse('index'));