Exemple #1
0
def register(request):
    registered = False

    if request.method == 'POST':
        #Get the relevant data from the post
        request.POST["username"] = request.POST["username"].lower()
        user_form = UserForm(data=request.POST)
        profile_form = AppUserForm(data=request.POST)

        #If the user is valid and they registered correctly, save
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            registered = True
        #Otherwise, throw back the errors
        else:
            print user_form.errors, profile_form.errors
    else:
        #Pull the forms for the get
        user_form = UserForm()
        profile_form = AppUserForm()

    #render the page with the forms
    return render(request, 'app/register.html',
                  {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})
Exemple #2
0
def register(request):

    if request.method == 'POST':
        from app.forms import UserForm

        user_form = UserForm(data=request.POST)

        if user_form.is_valid():
            secureKey = request.POST['secureKey']
            my_secret = request.POST['key']
            if (otp.valid_totp(token=secureKey, secret=my_secret) == False):
                request.session[
                    'message'] = 'the secure key is not correct please try again'
                return redirect("/")

            user = user_form.save()
            user.set_password(user.password)

            user.save()

            request.session['message'] = 'registration done please login'
            return redirect("/")
        else:
            request.session['error'] = user_form.errors
            return redirect("/")
def register(request):
 if request.user.is_authenticated():
   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)
            group = request.POST['Group']
            if group == '1':
                g = Group.objects.get(name='admin') 
                g.user_set.add(user)
            else:
                g = Group.objects.get(name='tester') 
                g.user_set.add(user)
            user.save()
            registered = True
            #strr=""+"alert('User is registerd')"
            #return HttpResponse(strr);
        else:
            print user_form.errors
   else:
        user_form = UserForm()
   return render_to_response(

            {'user_form': user_form,'registered': registered},
            context)
 else:
   return HttpResponseRedirect('/app/login/')
Exemple #4
0
def users_create(request):
    from django.conf import settings
    form_type = settings.GLOBAL_SETTINGS['FORM_CREATE']
    readonly = ''
    disabled = ''
    if form_type == settings.GLOBAL_SETTINGS['FORM_SHOW']:
        readonly = 'readonly'
        disabled = 'disabled'
    context = {
        'readonly': readonly,
        'disabled': disabled,
        'form_type': form_type,
        'roles': Role.objects.all()
    }
    context.update(settings.GLOBAL_SETTINGS)
    if request.method == 'GET':
        form = UserForm()
        context.update({'form': form})
        return render(request, 'users/form.html', context)
    else:
        form = UserForm(request.POST)
        if form.is_valid():
            new_user = User()
            new_user.first_name = form.cleaned_data.get('first_name')
            new_user.last_name = form.cleaned_data.get('last_name')
            new_user.email = form.cleaned_data.get('email')
            new_user.password = form.cleaned_data.get('password')
            new_user.role = form.cleaned_data.get('role')
            new_user.save()
            return redirect(reverse('users.index'))
        else:
            context.update({'form': form})
            return render(request, 'users/form.html', context)
Exemple #5
0
def add_volunteer(request):
	if request.user.is_authenticated():
		return HttpResponseRedirect(reverse('index')) # Logged in users shouldn't be able to sign up
	else:
		if request.method == "POST":
			user_form = UserCreationForm(request.POST)
			profile_form = UserForm(request.POST)
			if user_form.is_valid() and profile_form.is_valid():
				u_name = user_form.cleaned_data.get('username')
				u_pass = user_form.cleaned_data.get('password2')
				user = user_form.save() # Save the basic user with email/username and password
				user.first_name = profile_form.cleaned_data.get("first_name")
				user.last_name = profile_form.cleaned_data.get("last_name")
				user.phone = profile_form.cleaned_data.get("phone")
				user.address = profile_form.cleaned_data.get("address")
				user.save()
				# Still need to add skills they have here
				user = authenticate(username=u_name,
									password=u_pass)
				login(request, user)
				return HttpResponseRedirect(reverse('resources'))
		else:
			user_form = UserCreationForm()
			profile_form = UserForm()
		return render(request, "volunteer/new.html", { 
													'user_form': user_form, 
													'profile_form': profile_form,
													 })
Exemple #6
0
def add_volunteer(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(
            reverse('index'))  # Logged in users shouldn't be able to sign up
    else:
        if request.method == "POST":
            user_form = UserCreationForm(request.POST)
            profile_form = UserForm(request.POST)
            if user_form.is_valid() and profile_form.is_valid():
                u_name = user_form.cleaned_data.get('username')
                u_pass = user_form.cleaned_data.get('password2')
                user = user_form.save(
                )  # Save the basic user with email/username and password
                user.first_name = profile_form.cleaned_data.get("first_name")
                user.last_name = profile_form.cleaned_data.get("last_name")
                user.phone = profile_form.cleaned_data.get("phone")
                user.address = profile_form.cleaned_data.get("address")
                user.save()
                # Still need to add skills they have here
                user = authenticate(username=u_name, password=u_pass)
                login(request, user)
                return HttpResponseRedirect(reverse('resources'))
        else:
            user_form = UserCreationForm()
            profile_form = UserForm()
        return render(request, "volunteer/new.html", {
            'user_form': user_form,
            'profile_form': profile_form,
        })
def profileform():
    form = UserForm()
    date_joined = datetime.datetime.now()
    date_created = date_joined.strftime('%B %d,%Y')
    if request.method == 'POST':
        if form.validate_on_submit():
            #upload image
            image = form.photo.data
            filename = secure_filename(image.filename)
            image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            #Get form data inputs
            fname = form.firstname.data
            lname = form.lastname.data
            email = form.email.data
            bio = form.biography.data
            location = form.location.data
            gender = form.gender.data
            # add data to database
            user = UserProfile(firstname=fname,
                               lastname=lname,
                               email=email,
                               gender=gender,
                               location=location,
                               date_joined=date_created,
                               biography=bio,
                               filename=filename)
            db.session.add(user)
            db.session.commit()

            flash('You have sucessfully created a profile')
            return redirect(url_for('profiles'))
        flash_errors(form)
    return render_template('profileform.html', form=form)
Exemple #8
0
    def edit(self, request, pk):
        obj = self.Model.objects.get(id=pk)
        form = self.Form(request.POST or None, instance=obj)

        user_form = UserForm(request.POST or None, instance=obj.user)

        if request.method == "GET":
            return render(
                request, "shared/editor.html", {
                    "sidebar": self.name,
                    "forms": [form, user_form, PasswordForm],
                    "index_link": self.Model.list_link()
                })
        elif request.method == "POST":
            password_form = PasswordForm(request.POST or None)
            if user_form.is_valid() and form.is_valid(
            ) and password_form.is_valid():
                user, partner = user_form.save(commit=False), form.save(
                    commit=False)
                user.set_password(password_form.cleaned_data.get("password"))
                user.save()
                form.user = user
                form.save()
                return redirect(self.Model.list_link())
            return render(
                request, "shared/editor.html", {
                    "sidebar": self.name,
                    "forms": [form, user_form, PasswordForm],
                    "index_link": self.Model.list_link()
                })
Exemple #9
0
def my_profile():
    '''
    Show user their profile, let them edit it
    '''
    form = UserForm(obj=current_user)
    if request.method == 'GET':
        return render_template('my-profile.html', form=form)
    elif request.method == 'POST':
        #userProfile = json.loads(request.form.get('me'))
        #session['user-profile'] = userProfile
        #db.updateCoreProfile(userProfile)
        #flash('Your profile has been saved. <br/>You may also want to <a'
        #      'href="/my-expertise">tell us what you know</a>.')
        #session['has_created_profile'] = True
        form.populate_obj(current_user)
        if form.validate():
            db.session.add(current_user)
            db.session.commit()
            flash(lazy_gettext('Your profile has been saved. <br/>You may also want to <a'
                               'href="/my-expertise">tell us what you know</a>.'))
        else:
            flash(lazy_gettext(u'Could not save, please correct errors below: {}'.format(
                form.errors)))

        return render_template('my-profile.html', form=form)
Exemple #10
0
def register(request): #注册
	registered = False
	errors=[]
	if request.method == 'POST':
		user_form = UserForm(data = request.POST)
		profile_form = ProfileForm(data = request.POST)
		if user_form.is_valid() and profile_form.is_valid(): 
			user = user_form.save(commit = False)
			user.set_password(user.password)  #设置密码
			user.save()
			profile = profile_form.save(commit=False)  #不保存
			profile.user = user

			if 'userImage' in request.FILES:  #判断是否有上传头像
				profile.userImage = request.FILES['userImage']

			profile.save()  #保存
			registered = True
		else:
			errors.append(user_form.errors)
			errors.append(profile_form.errors)

	else:
		user_form = UserForm()
		profile_form = ProfileForm()
	return render(request, 'app/register.html', {'user_form':user_form, 'profile_form':profile_form, 'errors':errors,'registered':registered})
Exemple #11
0
 def add(self, request):
     forms = [self.Form, UserForm, PasswordForm]
     if request.method == "GET":
         return render(
             request, "shared/editor.html", {
                 "sidebar": self.name,
                 "forms": forms,
                 "index_link": self.Model.list_link(),
             })
     elif request.method == "POST":
         user_form = UserForm(request.POST)
         password_form = PasswordForm(request.POST)
         form = self.Form(request.POST)
         if user_form.is_valid() and password_form.is_valid(
         ) and form.is_valid():
             user, account = user_form.save(commit=False), form.save(
                 commit=False)
             user.role = self.role
             user.set_password(password_form.cleaned_data.get("password"))
             user.save()
             account.user = user
             account.save()
             return redirect(self.Model.list_link())
         return render(
             request, "shared/editor.html", {
                 "sidebar": self.name,
                 "form": [form, user_form, password_form],
                 "index_link": self.Model.list_link()
             })
def register(request):
    registered = False
    if request.method == "POST":
        user_form = UserForm(data=request.Post)
        profile_form = UserProfileInfoForm(data=request.Post)
        if user_form.is_valid and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user
            if 'profile_pic' in request > FILES:
                profile.profile_pic = request.FILES['profile_pic']
            profile.save()
            registered = True
        else:
            print(user_form.errors, profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileInfoForm()

    return render(
        request, 'app1/registation.html', {
            'user_form': user_form,
            'profile_form': profile_form,
            'registered': registered
        })
Exemple #13
0
def edit_user(user_id):
    user = User.query.filter_by(id=user_id).first()
    user_form = UserForm()
    if request.method == 'GET':
        user_form.name.data = user.name
        user_form.email.data = user.email
        user_form.username.data = user.username
    if request.method == 'POST':
        if user_form.validate_on_submit():
            name = request.form['name']
            email = request.form['email']
            username = request.form['username']
            password = sha256_crypt.encrypt(str(request.form['password']))

            # save user to database
            db.session.query(User).filter_by(id=user_id).update({
                "name":
                name,
                "email":
                email,
                "username":
                username,
                "password":
                password
            })
            db.session.commit()

            flash('User ' + name + ' successfully updated')
            return redirect(url_for('show_users'))

    flash_errors(user_form)
    return render_template('edit_user.html', form=user_form, usid=user_id)
def new():
    form = UserForm()
    
    if 'Content-Type' in request.headers and request.headers['Content-Type'] == 'application/json':
        users = db.session.query(User).all()
        return user_list_json(users)
    if request.method == 'GET':
        return render_template('new.html', form=form)
    elif form.validate():
        firstname = form.firstname.data
        lastname = form.lastname.data
        username = form.username.data
        sex = form.sex.data
        age = form.age.data
        image = form.image.data
        user = User(username ,firstname , lastname ,  age , sex ,'')
        filename = str(getrandbits(20)) + image.filename
        image.save(os.path.join("app/static", filename))
        user.file_location = filename
        db.session.add(user)
        db.session.commit()
        flash('New Profile created')
        return redirect(url_for('show' , user_id=user.user_id))
    else:
        return render_template('new.html' , form=form,errors=form.errors.items())
Exemple #15
0
def register(request):
    context = RequestContext(request)
    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']
            profile.save()
            registered = True
            new_user = authenticate(username=request.POST['username'], password=request.POST['password'])
            login(request, new_user)
            return HttpResponseRedirect('/user/')
        else:
            print(user_form.errors, profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    return JsonResponse({'errors': {'profile': profile_form.errors, 'user': user_form.errors}}, status=422);
Exemple #16
0
def performer_reg(request):
    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = PerformerProfileForm(data=request.POST)

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

            user.set_password(user.password)
            user.save()
            group = Group.objects.get(name='Band')
            user.groups.add(group)

            profile = profile_form.save(commit=False)
            profile.performer = user
            profile.save()
            registered = True

        else:
            print user_form.errors, profile_form.errors

    else:
        user_form = UserForm()
        profile_form = PerformerProfileForm()

    return render(request,
        'Gigstop/performer_registration.html',
        {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})
Exemple #17
0
def login(request):
	if request.method == 'GET':
		return render(request, 'login.html')

	if request.method == 'POST':
		# 校验登录页面传递的参数
		form = UserForm(request.POST)
		# 使用is_valid()判断是否校验成功
		if form.is_valid():
			# 登录设置
			# 	1,通过用户名和密码获取当前的user对象===>>auth.authenticate
			user = Users.objects.filter(username=form.cleaned_data['username']).first()
			if user:
				# 		可以通过username获取对象
				# 将user.password和form.cleaned_data['password']进行校验
				if check_password(form.cleaned_data['password'], user.password):
					# 校验用户名和密码都成功
					# 1、向cookie中设置随机参数ticket
					res = HttpResponseRedirect(reverse('users:index'))
					# set_cookie(key,value,max_age='',expires='')
					ticket = get_ticket()
					res.set_cookie('ticket', ticket, max_age=1000)
					# 2、向表user_ticket中存这个ticket和user的对应关系
					UserTicket.objects.create(user=user, ticket=ticket)
					return res
				else:
					return render(request, 'login.html')
			else:
				# 		登录系统的用户名不存在
				return render(request, 'login.html')
		#  	2,设置cookie中的随机值  ====>>auth.login()
		# 	3,设置user_ticket中的随机值
		else:
			return render(request, 'login.html')
def index():
    user_form = UserForm()

    if user_form.validate_on_submit():
        partial_user = User(email=user_form.email.data,
                            full_name=user_form.full_name.data,
                            user_type=user_form.user_type.data,
                            join_date=user_form.join_date.data,
                            next_police_check=user_form.next_police_check.data,
                            time_pref=user_form.time_pref.data,
                            day_pref=day_pref_to_binary(user_form.day_prefs.data))

        db.session.add(partial_user)
        db.session.commit()

        key = generate_invite_key()
        new_invite = Invite(user_id=partial_user.id, key=key)

        db.session.add(new_invite)
        db.session.commit()

        flash('Invitation created. The user can register at: ' + address + '/register/' + key, 'success')
        return redirect(url_for('invite.index'))

    data = {
        'editing': False,
        'title': 'Invite User',
        'form': user_form
    }

    return render_template('user/invite.html', **data)
def signup(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('private'))
    else:
        form_errors = None
        baseform_errors = None
        if request.method == 'POST':  # If the form has been submitted...
            #to update the user.. form = UserForm(request.POST, instance=request.user)
            form = UserForm(request.POST)
            baseform = BaseUserForm(request.POST)
            if form.is_valid() and baseform.is_valid():
                baseuser = baseform.save()
                newprofile = form.save(commit=False)
                newprofile.user = baseuser
                newprofile.save()
                #Custom stuff.....
                insert_nonrel("users", newprofile)
                return HttpResponseRedirect(reverse_lazy('private'))
            else:
                form_errors = form.errors
                baseform_errors = baseform.errors
                return render(request, 'app/signup.html', {'baseform': baseform, 'form': form, 'base_errors': baseform_errors, 'errors': form_errors})
        form = UserForm(request.GET)
        baseform = BaseUserForm(request.GET)
        return render(request, 'app/signup.html', {'baseform': baseform, 'form': form, 'base_errors': baseform_errors, 'errors': form_errors})
Exemple #20
0
def my_profile():
    '''
    Show user their profile, let them edit it
    '''
    form = UserForm(obj=current_user)
    if 'X-Upload-Too-Big' in request.headers:
        form.picture.errors = ('Sorry, the picture you tried to upload was too large',)
    if request.method == 'POST':

        if form.validate():
            form.populate_obj(current_user)

            if form.picture.has_file():
                set_user_picture(current_user, form.picture)

            db.session.add(current_user)
            db.session.commit()
            flash(gettext('Your profile has been saved.'))
            return redirect(url_for('views.my_expertise'))
        else:
            flash(gettext(u'Could not save, please correct errors.'))

    return render_template(
        'my-profile.html',
        form=form,
        page_config_json=json_blob(
            UPLOAD_PICTURE_URL=url_for('views.my_profile_upload_picture'),
            UPLOAD_PICTURE_SUCCESS=gettext("Your user picture has been changed."),
            UPLOAD_PICTURE_ERROR=gettext("An error occurred when uploading your user picture.")
        )
    )
Exemple #21
0
def profile():
    """Render the Add User page."""
    form = UserForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            fname = request.form['fname']
            lname = request.form['lname']
            email = request.form['email']
            location = request.form['location']
            gender = request.form['gender']
            bio = request.form['bio']
            currentdate = datetime.datetime.now()
            date = currentdate.strftime("%B %d, %Y")

            #photo = form.photo.data

            file = request.files['photo']
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            user = Profile(fname, lname, gender, email, location, bio,
                           filename, date)
            db.session.add(user)
            db.session.commit()

            flash('Succesfully Uploaded', 'success')
            return redirect(url_for('profiles'))

    #flash_errors(form)
    return render_template('profile.html', form=form)
Exemple #22
0
def register(request):
    if request.method == "POST":
        new_form = UserForm(request.POST)
        if new_form.is_valid():
            username = new_form.cleaned_data['username']
            firstname = new_form.cleaned_data['first_name']
            lastname = new_form.cleaned_data['last_name']
            email = new_form.cleaned_data['email']
            password = new_form.cleaned_data['password']
            confirmpassword = new_form.cleaned_data['confirm_password']
            print(password, confirmpassword)
            if password == confirmpassword:
                User.objects.create_user(username=username,
                                         first_name=firstname,
                                         last_name=lastname,
                                         email=email,
                                         password=password)
                messages.success(request, "User Registration Successfully !!")
                usr = auth.authenticate(username=username, password=password)
                auth.login(request, usr)
                return render(request, 'welcome.html')
            else:
                messages.error(
                    request, "Password and Confirm Password does not match !!")
                return HttpResponseRedirect('/register/')
    else:
        new_form = UserForm()
    return render(request, 'register.html', {"new_form": new_form})
Exemple #23
0
def add_user():
    user_form = UserForm()

    if request.method == 'POST':
        if user_form.validate_on_submit():
            # Get current time
            now = datetime.now(timezone("Singapore"))
            dt_string = now.strftime("%d/%m/%Y %H:%M:%S")

            # SELECT fullname FROM accounts WHERE username = user_form.name.data
            namefull = Account.query.filter_by(
                username=user_form.name.data).first()

            # Convert current day into integer, decode in base62 for validation
            dt_day = 10000 * now.year + 100 * now.month + now.day
            valid = base62.decode(str(dt_day))

            if user_form.valid.data == str(valid):
                # Save user's name, class and attendance time to database
                user = User(name=namefull.fullname,
                            classno=user_form.classno.data,
                            attendanceTime=dt_string)
                db.session.add(user)
                db.session.commit()

                flash('Attendance successfully taken!')
                return redirect(url_for('show_users'))

    flash_errors(user_form)
    return render_template('add_user.html', form=user_form)
Exemple #24
0
def restaurant_sign_up(request):
    user_form = UserForm()
    restaurant_form = RestaurantForm()

    if request.method == "POST":
        user_form = UserForm(request.POST)
        restaurant_form = RestaurantForm(request.POST, request.FILES)

        if user_form.is_valid() and restaurant_form.is_valid():
            new_user = User.objects.create_user(**user_form.cleaned_data)
            new_restaurant = restaurant_form.save(commit=False)
            new_restaurant.user = new_user
            new_restaurant.save()

            login(
                request,
                authenticate(username=user_form.cleaned_data["username"],
                             password=user_form.cleaned_data["password"]))

            return redirect(restaurant_home)

    return render(request, "restaurant/sign_up.html", {
        "user_form": user_form,
        "restaurant_form": restaurant_form
    })
Exemple #25
0
def criar():
    if current_user.is_active() and current_user.session_over():
        current_user.reset_token()

    if verify_dba(current_user):
        return redirect(url_for('despesas.listar'))

    form = UserForm()
    if form.validate_on_submit():
        uid = form.uid.data
        usuario = {
            'nome': form.nome.data,
            'sobrenome': form.sobrenome.data,
            'email': form.email.data,
            'departamento': form.departamento.data,
            'RD': form.representante.data,
            'DBA': form.dba.data,
            'Diretor': form.diretor.data
        }

        try:
            db.child('users').child(uid).update(usuario, current_user.idToken)
            return redirect(url_for('users.listar'))

        except Exception as e:
            mensagem = 'Não foi possível incluir este usuário.'
            print(e)
            flash(mensagem)
            return redirect(url_for('users.criar'))

    return render_template('users/criar.html', form=form)
Exemple #26
0
def user_reg(request):
     # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            registered = True

        else:
            print user_form.errors, profile_form.errors

    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    return render(request,
            'Gigstop/user_registration.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered} )
Exemple #27
0
def addProfile():
    form = UserForm()
    if request.method == "POST":
        if form.validate_on_submit() == True:
            #Gets the user input from the form
            fname = form.firstname.data
            lname = form.lastname.data
            gender = form.gender.data
            email = form.email.data
            location = form.location.data
            bio = form.bio.data
            date = format_date_joined()
            filename = assignPath(form.profile_picture.data)

            #create user object and add to database
            user = UserProfile(fname, lname, gender, email, location, bio,
                               date, filename)
            db.session.add(user)
            db.session.commit()

            # remember to flash a message to the user
            flash('User information submitted successfully.', 'success')
        else:
            flash('User information not submitted', 'danger')
        return redirect(
            url_for("profiles")
        )  # they should be redirected to a secure-page route instead
    return render_template("addprofile.html", form=form)
Exemple #28
0
def register():
    form = UserForm(request.form)
    if request.method == 'POST':
        if form.validate():
            level_id = form.level_id.data
            username = form.username.data
            email = form.email.data
            password = form.password.data
            no_telp = form.no_telp.data
            alamat = form.alamat.data
            AddUser = User(username=username,
                           email=email,
                           password=password,
                           no_telp=no_telp,
                           alamat=alamat,
                           level_id=level_id)
            db.session.add(AddUser)
            db.session.commit()
            return 'Data suda tersimpan'
        else:
            # mengambil daftar kesalahan yang muncul
            # pada saat proses validasi
            errors = form.errors.items()
            return render_template('register.html', form=form, errors=errors)
    return render_template('register.html', form=form)
Exemple #29
0
def register():
    """Api route for validating and saving Our users into database
    Additionalyl sends email and text upon User creations
    """
    form = UserForm(csrf_enabled=False)
    if form.validate():
        new_user = User.create(first_name=form.first_name.data, email=form.email.data,
                               phone_number=form.phone_number.data)

        response = jsonify(
            {'success': form.first_name.data, 'message': 'Success'})

        html = render_template("welcome.html", name=new_user.first_name)
        send_email(html, new_user.email)

        if new_user.phone_number == os.environ.get("PHONE"):
            send_async_sms("Welcome To Ready for it!")


        new_user.delete()
        response.status_code = 201
        return response

    response = jsonify({'error': 'Failed',
                        'message': form.errors})
    response.status_code = 400
    return response
Exemple #30
0
def my_profile():
    '''
    Show user their profile, let them edit it
    '''
    form = UserForm(obj=current_user)
    if 'X-Upload-Too-Big' in request.headers:
        form.picture.errors = ('Sorry, the picture you tried to upload was too large',)
    if request.method == 'POST':

        if form.validate():
            form.populate_obj(current_user)

            if form.picture.has_file():
                set_user_picture(current_user, form.picture)

            db.session.add(current_user)
            db.session.commit()
            flash(gettext('Your profile has been saved.'))
            return redirect(url_for('views.my_expertise'))
        else:
            flash(gettext(u'Could not save, please correct errors.'))

    return render_template(
        'my-profile.html',
        form=form,
        page_config_json=json_blob(
            UPLOAD_PICTURE_URL=url_for('views.my_profile_upload_picture'),
            UPLOAD_PICTURE_SUCCESS=gettext("Your user picture has been changed."),
            UPLOAD_PICTURE_ERROR=gettext("An error occurred when uploading your user picture."),
            REMOVE_PICTURE_URL=url_for('views.my_profile_remove_picture'),
            REMOVE_PICTURE_CONFIRM=gettext("Do you really want to remove your profile picture?"),
            REMOVE_PICTURE_SUCCESS=gettext("Your profile picture has been removed."),
            REMOVE_PICTURE_ERROR=gettext("An error occurred when removing your profile picture."),
        )
    )
Exemple #31
0
def register(request):
	context = RequestContext(request)
	
	registered = False
	
	if request.method == 'POST':
		user_form = UserForm(data=request.POST)
		profile_form = UserProfileForm(request.POST, request.FILES)
		
		if user_form.is_valid() and profile_form.is_valid():
			user = user_form.save()
			
			user.set_password(user.password)
			user.save()
			
			profile = profile_form.save(commit=False)
			profile.user = user
			
			if profile_form.is_multipart():
				picture = save_files(request.FILES['picture'])
				
			profile.save()
			
			registered = True
			
		else:
			print user_form.errors, profile_form.errors
	
	else:
		user_form =UserForm()
		profile_form = UserProfileForm()
	
	return render_to_response('app/register.html', {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, context)
Exemple #32
0
def signup(request):
    if request.method == 'POST':
        user_form = UserForm(request.POST)
        profile_form = ProfileForm(request.FILES)
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()

            auth_data = {
                'username': user.username,
                'password': user_form.cleaned_data['password1'],
            }
            u = auth.authenticate(request, **auth_data)
            if u is not None:
                auth.login(request, user)
                return redirect('/')

            return render(request, 'signup.html', {
                'form': user_form,
                **tags_and_users
            })

        return render(request, 'signup.html', {
            'form': user_form,
            **tags_and_users
        })
    return render(request, 'signup.html', tags_and_users)
Exemple #33
0
def adopter_register():
    form = UserForm()
    if form.validate_on_submit():

        if form.name.data:
            user_name = Adopter.query.filter_by(
                name=form.name.data).first()
            if user_name:
                flash('该用户名已注册,请重新填写用户名')
                return render_template('adopter_register.html', form=form)
        if form.mobile.data:
            user_mobile = Adopter.query.filter_by(
                mobile=form.mobile.data).first()
            if user_mobile:
                flash('该手机号已注册,请重新填写手机号')
                return render_template('adopter_register.html', form=form)
        new_register = Adopter()
        form.populate_obj(new_register)
        new_register.pwd = form.password.data
        db.session.add(new_register)
        try:
            db.session.commit()
            flash('注册成功')
        except Exception as e:
            db.session.rollback()
            flash('注册失败,请重试')
        return redirect(url_for('main.login'))
    return render_template(
        'adopter_register.html',
        form=form,
    )
Exemple #34
0
def addProperty():
    form= UserForm()
    if request.method == "POST":
        if form.validate_on_submit() == True:
            #Gets the user input from the form
            proptitle = form.propertytitle.data
            description = form.description.data
            noofrooms = form.noofrooms.data
            noofbathrooms = form.noofbathrooms.data
            price = form.price.data
            proptype = form.propertytype.data
            location = form.location.data
            filename = uploadPhoto(form.property_picture.data)

            #create user object and add to database
            user = UserProfile(proptitle,description,noofrooms,noofbathrooms,price,proptype, location, filename)
            db.session.add(user)
            db.session.commit()

             # remember to flash a message to the user
            flash('Property information uploaded successfully.', 'success')
        else:
            flash('Property information not uploaded', 'danger')
        return redirect(url_for("properties"))  # they should be redirected to a secure-page route instead
    return render_template("addproperty.html", form=form)
Exemple #35
0
def index():
    form = UserForm()

    if form.validate_on_submit():
        return redirect(url_for('index'))

    return render_template('index.html', form=form)
Exemple #36
0
def register(request):
	registered = False
	errors=[]
	if request.method == 'POST':
		user_form = UserForm(data = request.POST)
		profile_form = ProfileForm(data = request.POST)
		if user_form.is_valid() and profile_form.is_valid():
			user = user_form.save(commit = False)
			user.set_password(user.password)
			user.save()
			profile = profile_form.save(commit=False)
			profile.user = user
			print request.FILES

			# if request.FILES['userImage']:
			if 'userImage' in request.FILES:
				print 'has a Picture 1'
				profile.userImage = request.FILES['userImage']


			profile.save()
			registered = True
			# HttpResponseRedirect('app/')
		else:
			errors.append(user_form.errors)
			errors.append(profile_form.errors)
	else:
		user_form = UserForm()
		profile_form = ProfileForm()
	return render(request, 'app/register.html', {'user_form':user_form, 'profile_form':profile_form, 'errors':errors,'registered':registered})
Exemple #37
0
def register(request):
    context = RequestContext(request)
    username = request.POST['username']
    password = request.POST['password1']
    if request.method == 'POST':
    	form = UserForm(data=request.POST)
        critic_form = CriticForm()
        if form.is_valid():
            user = form.save()
            #user.set_password(user.password)
            user.save()

            critic = critic_form.save(commit=False)

            critic.user = user
            critic.image = '/static/img/profile.jpg'
            critic.save()
            user2 = authenticate(username=username, password=password)        
            if user2 is not None:
                if user.is_active:
                    auth_login(request, user2)
                    return HttpResponseRedirect('/feed')
                else:
                    pass
            else:
                return HttpResponseRedirect('/')
        else:
            return HttpResponseRedirect('/')
    else:
        form = UserForm()
        return HttpResponseRedirect('/')
def signup():
    form = UserForm()
    if form.validate_on_submit():
        username = form.username.data
        base_url = form.base_url.data
        try:
            r = requests.get(urljoin(base_url,'status'))
        except Exception as e:
            print type(e), ': ', e.message
            flash("That is not a proper url")
            return render_template("signup.html", form=UserForm())
        if r.status_code != 200:
            flash("The url did not return a 200 status on /status")
            return render_template("signup.html", form=UserForm())
        try:
            user = User(username, base_url)
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            print type(e), ': ', e.message
            flash("That name or url is taken. Please try another.")
            return render_template("signup.html", form=UserForm())
        flash("User %s signed up successfully!" % username)
        form = UserForm()
    return render_template("signup.html", form=form)
Exemple #39
0
def edit_profile():
    form = UserForm()
    user = User.query.filter(User.username == current_user.username).first()
    prof = user.profile.filter(Profile.user_id == user.id).first()
    social = user.social_links.filter(SocialLinks.user_id == user.id).first()

    if form.validate_on_submit():
        available = Profile.query.filter(Profile.user_id == user.id).first()
        social_avail = SocialLinks.query.filter(
            SocialLinks.user_id == user.id).first()
        if prof and social and available.user_id == user.id:
            available.first_name = form.first_name.data
            available.last_name = form.last_name.data
            available.img = form.img.data
            available.about = form.about.data
            available.timestamp = datetime.utcnow()
            social_avail.fb = form.fb.data
            social_avail.insta = form.insta.data
            social_avail.linkedIn = form.linkedIn.data
            social_avail.github = form.github.data
            social_avail.twitter = form.twitter.data
            social_avail.yt = form.yt.data
            db.session.commit()
        else:
            profile = Profile(first_name=form.first_name.data,
                              last_name=form.last_name.data,
                              img=form.img.data,
                              about=form.about.data,
                              fb=form.social.data,
                              user=user)
            db.session.add(profile)
            db.session.commit()
        flash('Your profile has been updated')
        return redirect(url_for('user', username=current_user.username))
    elif request.method == 'GET':
        user_id = user.profile.filter(
            Profile.user_id == current_user.id).first()
        s_user_id = user.social_links.filter(
            SocialLinks.user_id == current_user.id).first()
        if prof:
            form.first_name.data = user_id.first_name
            form.last_name.data = user_id.last_name
            form.img.data = user_id.img
            form.about.data = user_id.about
            form.fb.data = s_user_id.fb
            form.insta.data = s_user_id.insta
            form.linkedIn.data = s_user_id.linkedIn
            form.github.data = s_user_id.github
            form.yt.data = s_user_id.yt
            form.twitter.data = s_user_id.twitter
    if prof:
        img = prof.img
        return render_template('edit_profile.html',
                               title='Edit Profile',
                               img=img,
                               form=form)
    return render_template('edit_profile.html',
                           title='Edit Profile',
                           form=form)
Exemple #40
0
def register(request):
    # Like before, get the request's context.
    context = RequestContext(request)

    # A boolean value for telling the template whether the registration was successful.
    # Set to False initially. Code changes value to True when registration succeeds.
    registered = False

    # If it's a HTTP POST, we're interested in processing form data.
    if request.method == 'POST':
        # Attempt to grab information from the raw form information.
        # Note that we make use of both UserForm and UserProfileForm.
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

        # If the two forms are valid...
        if user_form.is_valid() and profile_form.is_valid():
            # Save the user's form data to the database.
            user = user_form.save()

            # Now we hash the password with the set_password method.
            # Once hashed, we can update the user object.
            user.set_password(user.password)
            user.save()

            # Now sort out the UserProfile instance.
            # Since we need to set the user attribute ourselves, we set commit=False.
            # This delays saving the model until we're ready to avoid integrity problems.
            profile = profile_form.save(commit=False)
            profile.user = user

            # Did the user provide a profile picture?
            # If so, we need to get it from the input form and put it in the UserProfile model.
            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            # Now we save the UserProfile model instance.
            profile.save()

            # Update our variable to tell the template registration was successful.
            registered = True

        # Invalid form or forms - mistakes or something else?
        # Print problems to the terminal.
        # They'll also be shown to the user.
        else:
            print user_form.errors, profile_form.errors

    # Not a HTTP POST, so we render our form using two ModelForm instances.
    # These forms will be blank, ready for user input.
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()

    # Render the template depending on the context.
    return render_to_response(
            'app/register.html',
            {'user_form': user_form, 'profile_form': profile_form, 'registered': registered},
            context)
Exemple #41
0
def test_user_form_validation(test_app, name, email, news_org, expect):
    """Tests the UserForm with different types of parameters."""
    with test_app.app_context():
        user_form = UserForm()
        user_form.name.data = name
        user_form.email.data = email
        user_form.news_org.data = news_org
        assert user_form.validate() == expect
Exemple #42
0
def form_view(request):
    form = UserForm
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            form.save(commit=True)

    return render(request, 'app/form.html', {'form_html': form})
Exemple #43
0
def add_users():
    if not current_user.is_authenticated:
        return redirect(url_for('login'))
    # add users to database

    # declare the user form
    form = UserForm(request.form)
    form.role.choices = [(x.id, x) for x in Role.query.all()]
    msg = None

    if request.method == 'GET':
        form.process()
        return render_template('layouts/default.html',
                               content=render_template('pages/add-user.html',
                                                       form=form,
                                                       message=msg))
    # check if both http method is POST and form is valid on submit
    if form.validate_on_submit():
        files_dir = os.path.join(os.path.dirname(app.instance_path),
                                 'app/static/files')
        # assign form data to variables
        name = request.form.get('fullname', '', type=str)
        unm = request.form.get('username', '', type=str)
        pwd = request.form.get('password', '', type=str)
        email = request.form.get('email', '', type=str)
        phone_no = request.form.get('phone_no', '', type=str)
        address = request.form.get('address', '', type=str)
        staff_no = request.form.get('staff_no', '', type=str)
        role_id = request.form.get('role', '', type=int)
        image = request.files.get('image')
        idcard = request.files.get('idcard')
        imagename = secure_filename(image.filename)
        idcardname = secure_filename(idcard.filename)
        # check if ID card image was chosen
        if idcardname == '':
            flash("Please select a valid ID card image")
            return redirect(url_for('add_users'))

        image.save(os.path.join(files_dir, 'photos', imagename))
        idcard.save(os.path.join(files_dir, 'idcards', idcardname))
        # see if user already exists
        user = User.query.filter_by(username=unm).first()
        if user:
            flash(
                f'Error: A user with the username {user.username} already exists!'
            )
        else:
            user = User(name, unm, email, pwd, phone_no, address, staff_no,
                        role_id, imagename)
            user.save()
            flash(
                'User successfully created! <br/> Return to viewing user list or add another user.'
            )
    else:
        flash('I am sorry but the details you entered cannot be saved :(')
    return render_template('layouts/default.html',
                           content=render_template('pages/add-user.html',
                                                   form=form))
Exemple #44
0
 def test_UserForm_invalid_without_password(self):
     form = UserForm(
         data={
             'username': "******",
             'first_name': "user",
             'last_name': "user",
             'email': "*****@*****.**"
         })
     self.assertFalse(form.is_valid())
Exemple #45
0
 def test_save(self):
     
     # Test the first choice.
     form_1 = UserForm(instance=self.user_1)
     self.assertEqual(self.user_1.pk, 1)
     
      # Test the second choice.
     form_2 = UserForm( instance=self.user_2)
     self.assertEqual(self.user_2.pk, 2)
Exemple #46
0
def manage_profile(request):
    form = UserForm(request.user)
    data = {}
    if request.method == 'POST':
        if form.validate(request.form):
            form.save()
            data['validate'] = u'成功しました。'
        else:
            data['validate'] = u'失敗しました。'
    data['form'] = form.as_widget()
    return render_to_response('app/manage-profile.html', data)
def home():
    form = UserForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User(username=form.data.get('username'))
        form.populate_obj(user)
        try:
            ss.add(db.session, user)
        except IntegrityError:
            db.session.rollback()
            form.username.errors.append('Username already exists!')
        else:
            return redirect(url_for('show_users'))
    return render_template('welcome.html', form=form)
Exemple #48
0
def banduser(openid):
    userform = UserForm()
    if userform.validate_on_submit():
        userinfo = User(
            openid=openid,
            stuid=userform.stuid.data,
            idcard=userform.idcard.data,
            libpass=userform.libpass.data,
            cardpass=userform.cardpass.data,
        )
        db.session.add(userinfo)
        db.session.commit()
    return render_template("user_band.html", userform=userform)
Exemple #49
0
def register(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)
			user.save()
			registered = True
		else:
			print user_form.errors
	else:
		user_form = UserForm()

	return render(request, 'app/register.html', {'user_form': user_form, 'registered': registered})
Exemple #50
0
def edit_user():
    this_user = User.query.get_or_404(request.args.get('id'))
    form = UserForm(username=this_user.username, name=this_user.name, email=this_user.email, tel=this_user.tel,
                    status=1 if this_user.status else 2, admin=this_user.admin)
    if form.validate_on_submit():
        this_user.email = form.email.data
        this_user.name = form.name.data
        this_user.tel = form.tel.data
        if form.password.data:
            this_user.password = form.password.data
        this_user.status = True if form.status.data == 1 else False
        this_user.admin = form.admin.data
        this_user.modify_time = datetime.now()
        db.session.add(this_user)
        db.session.commit()
        flash('用户信息已更新。', 'is-success')
        return redirect(url_for('.user'))
    return render_template('back/userEdit.html', form=form)
Exemple #51
0
def my_profile():
    '''
    Show user their profile, let them edit it
    '''
    form = UserForm(obj=current_user)
    if 'X-Upload-Too-Big' in request.headers:
        form.picture.errors = ('Sorry, the picture you tried to upload was too large',)
    if request.method == 'GET':
        return render_template('my-profile.html', form=form)
    elif request.method == 'POST':
        #userProfile = json.loads(request.form.get('me'))
        #session['user-profile'] = userProfile
        #db.updateCoreProfile(userProfile)
        #flash('Your profile has been saved. <br/>You may also want to <a'
        #      'href="/my-expertise">tell us what you know</a>.')
        #session['has_created_profile'] = True

        if form.validate():
            form.populate_obj(current_user)

            if form.picture.has_file():
                conn = S3Connection(current_app.config['S3_ACCESS_KEY_ID'],
                                    current_app.config['S3_SECRET_ACCESS_KEY'])
                bucket = conn.get_bucket(current_app.config['S3_BUCKET_NAME'])
                bucket.make_public(recursive=False)

                mimetype = mimetypes.guess_type(form.picture.data.filename)[0]

                k = bucket.new_key(current_user.picture_path)
                k.set_metadata('Content-Type', mimetype)
                k.set_contents_from_file(form.picture.data)
                k.make_public()

                current_user.has_picture = True

            db.session.add(current_user)
            db.session.commit()
            flash(gettext('Your profile has been saved. <br/>Please tell '
                          'us about your expertise below.'))
            return redirect(url_for('views.my_expertise'))
        else:
            flash(gettext(u'Could not save, please correct errors below'))

        return render_template('my-profile.html', form=form)
Exemple #52
0
def signup(request):
    registered = False
    if request.method == 'POST':
        form = UserForm(data=request.POST)
        if form.is_valid():
            user = form.save()
            user.set_password(user.password)
            user.save()
            registered = True
            user = authenticate(username=request.POST['username'],
                                password=request.POST['password'])
            login(request, user)
            return HttpResponseRedirect(reverse('app:index'))
        else:
            print form.errors
    else:
        form = UserForm()
    context = {'form': form, 'registered': registered}
    return render(request, 'app/signup.html', context)
Exemple #53
0
def loginUser(request):
    """Log in app to user"""
    if request.method == 'POST':
        form = UserForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponseRedirect('/myDashboard')
            else:
                flag = True
                return render_to_response("main/main.html", 
                                            {'flag': flag},
                                            context_instance=RC(request))

    else:
        return HttpResponseRedirect("/")
Exemple #54
0
def setting():
    """
    设置
    """
    # return "Hello, World!\nSetting!"
    form = UserForm(request.form)
    if request.method == 'GET':
        from user import get_user_row_by_id
        user_info = get_user_row_by_id(current_user.id)
        if user_info:
            form.nickname.data = user_info.nickname
            form.avatar_url.data = user_info.avatar_url
            form.email.data = user_info.email
            form.phone.data = user_info.phone
            form.birthday.data = user_info.birthday
            form.create_time.data = user_info.create_time
            form.update_time.data = user_info.update_time
            form.last_ip.data = user_info.last_ip
    if request.method == 'POST':
        if form.validate_on_submit():
            # todo 判断邮箱是否重复
            from user import edit_user
            from datetime import datetime
            user_info = {
                'nickname': form.nickname.data,
                'avatar_url': form.avatar_url.data,
                'email': form.email.data,
                'phone': form.phone.data,
                'birthday': form.birthday.data,
                'update_time': datetime.utcnow(),
                'last_ip': request.headers.get('X-Forwarded-For', request.remote_addr),
            }
            result = edit_user(current_user.id, user_info)
            if result == 1:
                flash(u'Edit Success', 'success')
            if result == 0:
                flash(u'Edit Failed', 'warning')
        flash(form.errors, 'warning')  # 调试打开
    flash(u'Hello, %s' % current_user.email, 'info')  # 测试打开
    return render_template('setting.html', title='setting', form=form)
Exemple #55
0
def register(request):
    registered=False
    user_form=UserForm(data=request.POST)
    profile_form=UserProfileForm(data=request.POST)
    
    if request.method=='POST':
        if user_form.is_valid() and profile_form.is_valid():
            user=user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save()
            profile.user = user
            profile.save()

            registered=True
    
        else:
            print (user_form.errors, profile_form.errors)

    return render(request,
            'app/register.html',
            context_instance=RequestContext(request,{'user_form': user_form, 'profile_form': profile_form, 'registered': registered} ))
Exemple #56
0
def my_profile():
    """
    Show user their profile, let them edit it
    """
    form = UserForm(obj=current_user)
    if "X-Upload-Too-Big" in request.headers:
        form.picture.errors = ("Sorry, the picture you tried to upload was too large",)
    if request.method == "GET":
        return render_template("my-profile.html", form=form)
    elif request.method == "POST":

        if form.validate():
            form.populate_obj(current_user)

            if form.picture.has_file():
                conn = S3Connection(current_app.config["S3_ACCESS_KEY_ID"], current_app.config["S3_SECRET_ACCESS_KEY"])
                bucket = conn.get_bucket(current_app.config["S3_BUCKET_NAME"])
                bucket.make_public(recursive=False)

                mimetype = mimetypes.guess_type(form.picture.data.filename)[0]

                k = bucket.new_key(current_user.picture_path)
                k.set_metadata("Content-Type", mimetype)
                k.set_contents_from_file(form.picture.data)
                k.make_public()

                current_user.has_picture = True

            db.session.add(current_user)
            db.session.commit()
            flash(gettext("Your profile has been saved."))
            return redirect(url_for("views.my_expertise"))
        else:
            flash(gettext(u"Could not save, please correct errors."))

        return render_template("my-profile.html", form=form)
Exemple #57
0
def index(request):
    ''' If logged in, direct to logged in user's profile page. Otherwise this is a login and registration form.
    '''
    
    # Redirect to user page if already logged in
    if request.user.is_authenticated():
        user = UserProfile.objects.get(user_id=request.user.id)
        return HttpResponseRedirect('/user/%d' % user.id)
    
    # Otherwise this is a registration page    
    if request.method == 'POST':
        user_form = UserForm(data=request.POST)
        profile_form = UserProfileForm(data=request.POST)

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

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

            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            
            user = authenticate(username=request.POST['username'], password=request.POST['password'])
            login(request, user)
            user = UserProfile.objects.get(user_id=user.id)
            return HttpResponseRedirect('/user/%d' % user.id)
        else:
            print user_form.errors, profile_form.errors  
    else:
        user_form = UserForm()
        profile_form = UserProfileForm()
    
    context = {'user_form': user_form, 'profile_form': profile_form}
    return render(request, 'app/index.html', context)    
Exemple #58
0
def register(request):
	registered = False
	if request.method == 'POST':
		user_form = UserForm(request.POST)
		profile_form = UserProfileForm(request.POST)
		if user_form.is_valid() and profile_form.is_valid():
			user = user_form.save()
			user.set_password(user.password)
			user.save()
			profile = profile_form.save(commit = False)
			profile.user = user

			if 'photo' in request.FILES:
				profile.photo = request.FILES['photo']

			profile.save()
			registered = True
		else:
			print user_form.errors, profile_form.errors
	else:
		user_form = UserForm()
		profile_form = UserProfileForm()
	dict = {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}
	return render(request, 'blog/register.htm', dict)
Exemple #59
0
def add_volunteer(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('index')) # Logged in users shouldn't be able to sign up
    else:
        if request.method == "POST":
            profile_form = UserForm(request.POST)
            if profile_form.is_valid():
                user = Volunteer()
                user.first_name = profile_form.cleaned_data.get("first_name")
                user.last_name = profile_form.cleaned_data.get("last_name")
                user.email = profile_form.cleaned_data.get("email")
                user.phone = profile_form.cleaned_data.get("phone")
                user.address = profile_form.cleaned_data.get("address")

                user.save()
                
                user_resources = profile_form.cleaned_data.get("has_resources")
                
                user_resource_objects = [Resource.objects.filter(name=r).first() for r in user_resources]

                for r in user_resource_objects:
                    user.has_resources.add(r)
                
                user.save()
                
                    

        
                # Grab email set dependent on language value (may need to change values)
                if request.LANGUAGE_CODE == 'es':
                    from email_texts import spanish_version_emails as emails
                else:
                    from email_texts import english_version_emails as emails
                    
                # Find some nearby locations that need the things the volunteer has
                coords = find_search_coordinates(user.address)
                
                within_radius = []
                
                if len(user_resource_objects) == 0:
                    #do not include anything about local orgs if the user specified no resources
                    pass
                elif not coords:
                    #do not include local orgs if the coordinates weren't found
                    pass
                elif len(user_resource_objects) == 1 and user_resource_objects[0].name.lower() == "other":
                    #do not include local orgs if the only resource is "other"
                    pass
                else:
                    locations = Location.objects.select_related('provider').exclude(provider__approved=False)
                    locations = locations.filter(resources_needed__in=user_resource_objects)
                    locations = set(locations)
                    
                    for location in locations:
                        dist = vincenty(
                            (location.latitude, location.longitude), 
                            (coords['latitude'], coords['longitude'])
                            ).miles
                    
                        if dist <= RADIUS_DISTANCE:
                            within_radius.append((location,round(dist,1)))
                        
                    
                    within_radius.sort(key=lambda tup: tup[1])
                    
                    within_radius = within_radius[0:3] #only display the 3 nearest locations in email
                
                vol_conf_texts = emails['volunteer_signup']['confirmation']
                if len(within_radius) > 0:
                    getting_started = vol_conf_texts["here_are_some_orgs"].decode('utf-8')
                    for location_tuple in within_radius:
                        location = location_tuple[0]
                        dist = location_tuple[1]
                        
                        location_resources = []
                        for r in location.resources_needed.all():
                            if r.name in emails['resource_translation']:
                                location_resources.append(emails['resource_translation'][r.name])

                        location_info = [location.provider.name.decode('utf-8'),
                                        location.address,location.phone.decode('utf-8'),
                                        location.provider.URL.decode('utf-8'),
                                        "{0} {1}".format(dist,vol_conf_texts["miles_from_you"].decode('utf-8')),
                                        "{0} {1}".format(vol_conf_texts["resources_needed"].decode('utf-8'),', '.join(location_resources)),
                                        '\n\n']
                        getting_started = getting_started.decode('utf-8')
                        getting_started += '\n'.join(location_info)
                    getting_started += vol_conf_texts["find_some_more_orgs"].decode('utf-8')
                else:
                    getting_started = vol_conf_texts["find_some_orgs"].decode('utf-8')
                    
                getting_started += " http://www.buscandomaryland.com/resources/volunteer"
                    
                # Grab admin email list (if not already grabbed or stored somewhere else)
                admin_email_list = [admin_email_address]
                
                vol_resources = []
                for r in user_resources:
                    if r in emails['resource_translation']:
                        vol_resources.append(emails['resource_translation'][r.lower()])
                
                if len(vol_resources) > 0:
                    vol_resources = ','.join(vol_resources)
                else:
                    vol_resources = "None"
        
                # Build confirmation email
                email = emails['volunteer_signup']['confirmation']
                volunteer_email_body = email['body'].format(firstname=user.first_name,
                    vol_username=user.email,
                    vol_location=user.address,
                    resources_available=vol_resources,
                    getting_started = getting_started)
                confirmation_email = (email['subject'], volunteer_email_body, email['from'], [user.email])
        
                # Build admin notification email
                email = emails['volunteer_signup']['admin']
                admin_email_body = email['body'].format(vol_username=user.email)
                admin_email = (email['subject'], admin_email_body, email['from'], admin_email_list)
        
                # Send Them
                try:
                    send_mass_mail((admin_email, confirmation_email), fail_silently=False)
                except:
                    pass
                #end of code for confirmation e-mail
                
                
                # Still need to check for saving of skills they have here
                return HttpResponseRedirect(reverse('resources'))
        else:
            profile_form = UserForm()
        return render(request, "volunteer/new.html", { 'profile_form': profile_form})