コード例 #1
0
def profile():
    """Render the website's profile page."""
    profilePage = ProfileForm()

    if request.method == 'POST':
        if profilePage.validate_on_submit():

            firstName = profilePage.firstName.data
            lastName = profilePage.lastName.data
            gender = profilePage.gender.data
            email = profilePage.email.data
            location = profilePage.location.data
            biography = profilePage.biography.data
            photo = profilePage.photo.data

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

            profile = Profile(first_name=firstName,
                              last_name=lastName,
                              gender=gender,
                              email=email,
                              location=location,
                              biography=biography,
                              profile_picture="uploads/" + filename)
            db.session.add(profile)
            db.session.commit()

            flash('New Profile Created!', 'success')
            return redirect(url_for('profiles'))
        else:
            flash_errors(profilePage)

    return render_template('profile.html', form=profilePage)
コード例 #2
0
ファイル: routes.py プロジェクト: MBkkt/TaskManager
def profile(user_id):
    if current_user.id != user_id:
        return redirect(request.args.get('next') or url_for('index'))
    user = User.query.filter_by(id=user_id).first()
    form = ProfileForm()
    if form.validate_on_submit():
        User.edit(user, {
            'delete': form.delete.data,
            'login': form.login.data,
            'email': form.email.data,
            'first_name': form.first_name.data,
            'last_name': form.last_name.data,
            'type': form.type.data,
        })
        if form.delete.data:
            flash('Profile is deleted', 'primary')
        else:
            flash('Profile is edited', 'primary')
        return redirect(url_for('login'))
    if request.method == 'GET':
        form.login.data = user.login
        form.email.data = user.email
        form.first_name.data = user.first_name
        form.last_name.data = user.last_name
        form.type.data = user.type
    return render_template(
        'profile.html', title='Profile', form=form,
        current_user=current_user
    )
コード例 #3
0
def profile():
    form = ProfileForm()
    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.photo.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("profile.html", form=form)
コード例 #4
0
def edit_profile(username):
    """Endpoint to edit a user profile."""
    form = ProfileForm()
    if form.validate_on_submit():
        if current_user.type_of_user in [
                1, 2
        ] or username == current_user.username:
            user = User.query.filter_by(username=username).first_or_404()
            user.username = form.username.data
            user.email = form.email.data
            user.edit_date = datetime.datetime.utcnow().date()
            if current_user.type_of_user in [2]:
                user.type_of_user = int(form.type_of_user.data)
            user.edit_uid = current_user.id
            db.session.commit()
            flash("Your changes have been saved.")
            return redirect(url_for("edit_profile", username=user.username))
        else:
            flash("You are not authorised to view this!")
            return redirect(url_for("index"))
    elif request.method == "GET":
        if current_user.type_of_user in [
                1, 2
        ] or username == current_user.username:
            user = User.query.filter_by(username=username).first_or_404()
            form.username.data = user.username
            form.email.data = user.email
            form.type_of_user.data = str(user.type_of_user)
            return render_template("edit_profile.html",
                                   title="Edit Profile",
                                   form=form)
        else:
            flash("You are not authorised to view this!")
            return redirect(url_for("index"))
コード例 #5
0
ファイル: views.py プロジェクト: DScott19/info3180-project1
def profile():
    form = ProfileForm()
    if request.method == "POST" and form.validate_on_submit():
        firstname = form.firstname.data
        lastname = form.lastname.data
        email = form.email.data
        location = form.location.data
        gender = form.gender.data
        biography = form.biography.data
        photo = form.photo.data
        filename = secure_filename(photo.filename)
        photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        user = UserProfile(first_name=firstname,
                           last_name=lastname,
                           email=email,
                           location=location,
                           gender=gender,
                           biography=biography,
                           filename=filename,
                           created_on=format_date_joined())
        db.session.add(user)
        db.session.commit()
        flash('Profile was successfully added', 'success')
        return redirect(url_for('profiles'))
    else:

        return render_template('profile.html', form=form)
コード例 #6
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)
コード例 #7
0
ファイル: views.py プロジェクト: laskeym/carwash_site
def profile():
    profile = UserProfile.query.filter_by(user_id=current_user.id).first()
    form = ProfileForm(obj=profile)
    if form.validate_on_submit():
        if profile:
            form.populate_obj(profile)
            db.session.commit()

            flash('Profile Information has been saved!')
            return redirect(url_for('account'))
        new_profile = UserProfile(user_id=current_user.id,
                                  first_name=form.first_name.data,
                                  last_name=form.last_name.data,
                                  birth_date=form.birth_date.data,
                                  address_1=form.address_1.data,
                                  address_2=form.address_2.data,
                                  city=form.city.data,
                                  state=form.state.data,
                                  zip=form.zip.data)

        db.session.add(new_profile)
        db.session.commit()

        flash('Profile Information has been saved!')
        return redirect(url_for('account'))
    return render_template('profile.html', form=form)
コード例 #8
0
def register():
    """ Renders user registration page"""
    form = ProfileForm()

    if request.method == 'POST' and form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        firstname = form.firstname.data
        lastname = form.lastname.data
        location = form.location.data
        email = form.email.data
        biography = form.biography.data

        photo = form.profile_photo.data
        filename = secure_filename(photo.filename)
        #photo.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
        photo.save(
            os.path.join("./app", app.config['PROFILE_IMG_UPLOAD_FOLDER'],
                         filename))

        date_created = datetime.datetime.now().strftime("%B %d, %Y")

        new_user = UserProfile(username=username,
                               password=password,
                               firstname=firstname,
                               lastname=lastname,
                               biography=biography,
                               profile_photo=filename,
                               location=location,
                               joined_on=date_created,
                               email=email)
        db.session.add(new_user)
        db.session.commit()

        return jsonify(message="User successfully registered")
コード例 #9
0
def profile_form_submit(user_id):
    form = ProfileForm()
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        profile = Profile.query.filter_by(user_id=user_id).first()
        if profile:
            profile.about = form.data['about'],
            profile.first_name = form.data['first_name'],
            profile.last_name = form.data['last_name'],
            profile.phone_number = form.data['phone_number'],
            profile.location = form.data['location'],
            profile.work = form.data['work'],
            profile.language = form.data['language'],
        else:
            profile = Profile(about=form.data['about'],
                              first_name=form.data['first_name'],
                              last_name=form.data['last_name'],
                              phone_number=form.data['phone_number'],
                              location=form.data['location'],
                              work=form.data['work'],
                              language=form.data['language'],
                              user_id=user_id)

        db.session.add(profile)
        db.session.commit()
        return profile.to_dict()
コード例 #10
0
ファイル: views.py プロジェクト: Yogaz101/project1
def profile():
    """Render the website's profile page"""
    form = ProfileForm()
    us_Id = len(UserProfile.query.all())

    if request.method == "POST" and form.validate_on_submit():

        first_name = form.first_name.data
        last_name = form.last_name.data
        gender = form.gender.data
        location = form.location.data
        email = form.email.data
        bio = form.biography.data
        date = format_date(get_date())
        image = form.image.data
        imageName = first_name + last_name + str(us_Id + 1)

        newUser = UserProfile(first_name=first_name,
                              last_name=last_name,
                              gender=gender,
                              location=location,
                              email=email,
                              biography=bio,
                              created_on=date,
                              profilePic=imageName)
        db.session.add(newUser)
        db.session.commit()

        image.save("app/static/profilepictures/" + imageName + ".png")

        flash("New User Profile Created", "success")
        return redirect(url_for("profiles"))

    return render_template("profile.html", form=form)
コード例 #11
0
ファイル: views.py プロジェクト: JahFriend/info3180
def profile():
    form = ProfileForm()
    if request.method == "POST" and form.validate_on_submit():
        photo = form.Pic.data
        name = form.firstName.data + " " + form.lastName.data
        gender = form.gender.data
        email = form.email.data
        location = form.location.data
        bio = form.biography.data

        filename = secure_filename(photo.filename)
        photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #print(os.path.join(
        #  app.config['UPLOAD_FOLDER'], filename
        #))
        created_on = getDate()
        user = Users(created_on, name, location, filename, gender, email, bio)

        db.session.add(user)
        db.session.commit()

        flash("user was successfully added", 'success')
        return redirect(url_for("home"))
    print(form.errors)
    return render_template("profile.html", form=form)
コード例 #12
0
def add_profile():
    """GET provides the profile form while POST stores profile"""
    profileform = ProfileForm()
    if request.method == 'POST' and profileform.validate_on_submit():
        # Get values from form
        fname = request.form['first_name']
        lname = request.form['last_name']
        gender = request.form['gender']
        email = request.form['email']
        location = request.form['location']
        bio = request.form['bio']

        file = profileform.photo.data
        filename = secure_filename(file.filename)
        file.save(os.path.join(path, filename))

        try:
            profile = UserProfile(fname, lname, gender, email, location, bio,
                                  filename)
            db.session.add(profile)
            db.session.commit()
            flash('Profile Saved', 'success')
            return redirect(url_for('view_profiles'))
        except:
            flash("Profile failed to save", 'danger')
    return render_template('add_profile.html', form=profileform)
コード例 #13
0
ファイル: views.py プロジェクト: leonff14/info3180-pro2
def newprofile():
    error = None
    form = ProfileForm()
    if request.method == 'POST':
        firstname = request.form['firstname']
        lastname = request.form['lastname']
        sex = request.form['sex']
        age = int(request.form['age'])
        email = request.form['email']
        password = request.form['password']
        salt = uuid.uuid4().hex
        salty = hashlib.sha256(salt.encode() +
                               password.encode()).hexdigest() + ':' + salt
        hash_object = hashlib.sha256(email + salty)
        hashed = hash_object.hexdigest()
        newProfile = myprofile(firstname=firstname,
                               lastname=lastname,
                               email=email,
                               password=password,
                               sex=sex,
                               age=age,
                               hashed=hashed)
        db.session.add(newProfile)
        db.session.commit()
        return redirect('/')
    form = ProfileForm()
    return render_template('registration.html', form=form, error=error)
コード例 #14
0
ファイル: views.py プロジェクト: TafLew97/info3180-project1
def profile():
    form = ProfileForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            firstname = form.firstname.data
            lastname = form.lastname.data
            email = form.email.data
            biography = form.biography.data
            location = form.location.data
            gender = form.gender.data

            created_on = format_date_joined()

            photo = form.photo.data
            filename = secure_filename(photo.filename)
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            User = UserProfile(firstname=firstname,
                               lastname=lastname,
                               email=email,
                               location=location,
                               gender=gender,
                               created_on=created_on,
                               filename=filename,
                               biography=biography)
            db.session.add(User)
            db.session.commit()

            flash("User Created Successfully!")
            return redirect(url_for("viewprofiles"))
        else:
            flash_errors(form)

    return render_template('profile.html', form=form)
コード例 #15
0
def profile(username):
    username = username.lower()
    preparedQuery = 'SELECT * FROM Users WHERE username=?;'
    user = safe_query(preparedQuery, (username,), one=True)
    edit = False
    form = ProfileForm()

    if username == current_user.username:
        if form.validate_on_submit():
            preparedQuery = 'UPDATE Users ' \
                            'SET education=?, employment=?, music=?, movie=?, nationality=?, birthday=? ' \
                            'WHERE id=?;'
            data = (form.education.data, form.employment.data, form.music.data, form.movie.data, form.nationality.data,
                    form.birthday.data, current_user.id)
            safe_query(preparedQuery, data)
            return redirect(url_for('profile', username=username))
        elif form.is_submitted():
            edit = True
        if user['education'] != 'Unknown':
            form.education.data = user['education']
        if user['nationality'] != 'Unknown':
            form.nationality.data = user['nationality']
        if user['music'] != 'Unknown':
            form.music.data = user['music']
        if user['movie'] != 'Unknown':
            form.movie.data = user['movie']
        if user['employment'] != 'Unknown':
            form.employment.data = user['employment']
        if user['birthday'] != 'Unknown':
            form.birthday.data = datetime.strptime(user['birthday'], '%Y-%m-%d')

    return render_template('profile.html', title='Profile', user=user, form=form, edit=edit)
コード例 #16
0
ファイル: views.py プロジェクト: Rushane/info3180-project1
def profile():
    form = ProfileForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            firstname = form.firstname.data
            lastname = form.lastname.data
            location = form.location.data
            email = form.email.data
            biography = form.biography.data
            gender = form.gender.data

            #form.photo.label.text = 'Browse...'
            photo = form.photo.data
            filename = secure_filename(photo.filename)
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

            date_created = datetime.datetime.now().strftime("%B %d, %Y")

            new_user = UserProfile(firstname=firstname,
                                   lastname=lastname,
                                   biography=biography,
                                   photo=filename,
                                   gender=gender,
                                   location=location,
                                   created_on=date_created,
                                   email=email)

            db.session.add(new_user)
            db.session.commit()

            flash('Profile added', 'success')
            return redirect(url_for("profiles"))
    return render_template('profile.html', form=form)
コード例 #17
0
def profile():
    """Render the website's profile page to add a profile."""
    form = ProfileForm()
    if request.method == "POST" and form.validate_on_submit():
        firstname = form.firstname.data
        lastname = form.lastname.data
        gender = form.gender.data
        email = form.email.data
        location = form.location.data
        biography = form.biography.data
        photo = form.photo.data
        date = datetime.today().strftime('%B %d, %Y')

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

        profile = Profile(first_name=firstname,
                          last_name=lastname,
                          gender=gender,
                          email=email,
                          location=location,
                          biography=biography,
                          photo=filename,
                          date=date)
        db.session.add(profile)
        db.session.commit()
        flash('Profile Successfully added.', 'success')
        profiles = Profile.query.all()
        return render_template('profiles.html', profiles=profiles)

    return render_template('profile.html', form=form)
コード例 #18
0
def profile():

    form = ProfileForm()
    Id = len(UserProfile.query.all())
    if request.method == "POST" and form.validate_on_submit():
        first_name = form.first_name.data
        last_name = form.last_name.data
        gender = form.gender.data
        email = form.email.data
        location = form.location.data
        biography = form.biography.data
        image = form.image.data
        joined_on = form.joined_on.data
        img_name = first_name + last_name + str(Id + 1)

        NewUser = UserProfile(first_name=first_name,
                              last_name=last_name,
                              gender=gender,
                              email=email,
                              location=location,
                              biography=biography,
                              image=image,
                              joined_on=joined_on)

        db.session.add(NewUser)
        db.session.commit()

        image.save("app/static/profilepictures/" + img_name + ".png")

        flash("New User Profile Created", "success")
        return redirect(url_for("profiles"))

    return render_template('profile.html', form=form)
コード例 #19
0
ファイル: views.py プロジェクト: massem100/info3180-project1
def addProfile():
    profileform = ProfileForm()
    if request.method == "POST" and profileform.validate():
        if profileform.validate_on_submit():
            first_name = profileform.first_name.data
            last_name = profileform.last_name.data
            gender = profileform.gender.data
            email = profileform.email.data
            location = profileform.location.data
            bio = profileform.bio.data
            photo = profileform.photo.data
            
            photo_filename = secure_filename(photo.filename)
            photo.save(os.path.join(app.config['UPLOAD_FOLDER'], photo_filename))
            
            profile = UserProfile(first_name,last_name,gender,location, email,bio, photo_filename)
            db.session.add(profile)
            db.session.commit()
            # photo.save(os.path.join(app.config))
            flash('User sucessfully added', 'success')
            return redirect(url_for('profiles'))
    else: 
        return render_template('addProfile.html', form = profileform)

    if request.method =="GET":
        return render_template('addProfile.html')
コード例 #20
0
def profile():
    form = ProfileForm()
    # if current_user.is_authenticated:
    #     # if user is already logged in, just redirect them to our secure page
    #     # or some other page like a dashboard
    #     return redirect(url_for('secure_page'))

    # Here we use a class of some kind to represent and validate our
    # client-side form data. For example, WTForms is a library that will
    # handle this for us, and we use a custom LoginForm to validate.
    if request.method == 'POST' and form.validate_on_submit():
        firstName = form.fname.data
        lastName = form.lname.data
        email = form.email.data
        location = form.location.data
        sex = form.sex.data
        bio = form.bio.data
        if form.photo.data:
            #filename = secure_filename(form.fle.data.filename)
            #form.fle.data.save('uploads/' + filename)
            im = request.files['photo']
            im_fn = form.fname.data + '_' + secure_filename(im.filename)
            file_path = os.path.join(app.config['UPLOAD_FOLDER'], im_fn)
            im.save(file_path)
        user = UserProfile.query.filter_by(email=email).first()
        #if user is not None and check_password_hash(user.password, password):
        if user is None:
            profile = UserProfile(firstName, lastName, location, email, sex,
                                  bio, datetime.now(), im_fn)
            db.session.add(profile)
            db.session.commit()
        return redirect(url_for('showProfiles'))
    flash_errors(form)
    return render_template('form.html', form=form)
コード例 #21
0
def profile():
    # Instantiate your form class
    if request.method == 'GET':
        form = ProfileForm()
        return render_template('profile.html', form=form)

    # Validate file upload on submit
    form = ProfileForm()
    if request.method == 'POST' and form.validate_on_submit():
        # Get file data and save to your uploads folder
        F_Name = form.F_Name.data
        L_Name = form.L_Name.data
        Gender = form.Gender.data
        Email = form.Email.data
        Location = form.Location.data
        Biography = form.Biography.data
        file = form.file.data
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        profile = Profile(F_Name, L_Name, Gender, Email, Location, Biography,
                          filename,
                          datetime.datetime.now().strftime("%B %d, %Y"))
        db.session.add(profile)
        db.session.commit()

        flash('Profile Added', 'success')
        return redirect(url_for('profiles', images=get_uploaded_images()))
    return redirect(url_for('home'))
コード例 #22
0
ファイル: __init__.py プロジェクト: GautamP7/DataMart
def profile():
    form1 = ProfileForm()
    form2 = PasswordForm()
    user = User.query.filter_by(UserAccountId=current_user.get_id()).first()

    if form1.submit.data and form1.validate_on_submit():
        if user.Profile == None:
            user_profile = UserProfile(FirstName=form1.first_name.data, LastName=form1.last_name.data, DOB=form1.dob.data, \
                Phone=form1.phone.data, Address=form1.address.data, Country=form1.country.data, owner=user)
            db.session.add(user_profile)
            db.session.commit()
        else:
            user.Profile.FirstName = form1.first_name.data
            user.Profile.LastName = form1.last_name.data
            user.Profile.DOB = form1.dob.data
            user.Profile.Phone = form1.phone.data
            user.Profile.Address = form1.address.data
            user.Profile.Country = form1.country.data
            db.session.commit()
        flash('Changes succesfully saved!')
        return redirect(url_for('profile'))

    if form2.update.data and form2.validate_on_submit():
        if user is None or not user.check_password(form2.password.data):
            flash('Invalid current password')
            return redirect(url_for('profile'))
        user.set_password(form2.new_password.data)
        db.session.commit()
        flash('Password succesfully updated!')
        return redirect(url_for('profile'))

    return render_template('account-profile.html',
                           title='Profile',
                           form1=form1,
                           form2=form2)
コード例 #23
0
def profile(request):
    user = User.objects.get(id = request.user.id)
    try:
        user.applicant
    except:
        return HttpResponseRedirect(reverse('index'))
    applicant = user.applicant
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            user.first_name = form.cleaned_data.get('first_name')
            user.last_name = form.cleaned_data.get('last_name')
            user.save()
            applicant.city = form.cleaned_data.get('city')
            applicant.state = form.cleaned_data.get('state')
            applicant.country = form.cleaned_data.get('country')
            applicant.zipcode = form.cleaned_data.get('zipcode')
            applicant.phone = form.cleaned_data.get('phone')
            applicant.dob = form.cleaned_data.get('dob')
            applicant.languages = form.cleaned_data.get('languages')
            applicant.communities = form.cleaned_data.get('communities')
            applicant.working_now = form.cleaned_data.get('working_now')
            applicant.school_now = form.cleaned_data.get('school_now')
            applicant.time_commitment = form.cleaned_data.get('time_commitment')
            applicant.past_applicant = form.cleaned_data.get('past_applicant')
            applicant.referral = form.cleaned_data.get('referral')
            applicant.save()
            return HttpResponseRedirect(reverse('index'))
    else:
        userinfo = model_to_dict(user)
        applicationinfo = model_to_dict(applicant)
        allinfo = dict(userinfo.items() + applicationinfo.items())
        form = ProfileForm(initial=allinfo)
    return render(request, 'profile.html', {'form':form})
コード例 #24
0
ファイル: views.py プロジェクト: JHSaint/OOD-project
def profile():
    form = ProfileForm()
    if request.method == "POST":
        if form.validate_on_submit():

            #Gets the user input from the form
            fname = form.first_name.data
            lname = form.last_name.data
            username = form.Username.data
            password = form.Password.data
            account_type = form.account_type.data
            date = format_date_joined()
            pic = assignPathU(form.pic.data)
            rsvplst = ""

            #create user object and add to database
            user = UserProfile(fname, lname, username, password, account_type,
                               pic, date, rsvplst)
            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("login")
        )  # they should be redirected to a secure-page route instead
    return render_template("profile.html", form=form)
コード例 #25
0
ファイル: views.py プロジェクト: zhoulunhao/spider_web
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})
コード例 #26
0
ファイル: views.py プロジェクト: yoyomaster/spider_web
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})
コード例 #27
0
def profile():
    form = ProfileForm()
    if request.method == "POST" and form.validate_on_submit():

        # fname = form.fname.data
        # lname = form.lname.data
        # email = form.email.data
        # location = form.location.data
        # gender = form.gender.data
        # biography = form.biography.data

        file = form.image.data
        filename = secure_filename(file.filename)
        file.save(os.path.join(path, filename))

        user = UserProfile(
            request.form['fname'],
            request.form['lname'],
            request.form['email'],
            request.form['location'],
            request.form['gender'],
            request.form['bio'],
            filename,
            # datetime.datetime.now()
            datetime.datetime.now().strftime("%B %d, %Y"))

        db.session.add(user)
        db.session.commit()

        flash('Profile Saved', 'success')
        return redirect(url_for("profiles"))
    return render_template("profile.html", form=form)
コード例 #28
0
def profile():
    form = ProfileForm()
    if request.method == "POST" and form.validate_on_submit():
        profilePhoto = form.photo.data
        filename = secure_filename(profilePhoto.filename)
        profilePhoto.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        newUser = UserProfile(
            # first_name = form.first_name.data,
            # last_name = form.last_name.data,
            # email = form.email.data,
            # location = form.location.data,
            # gender = form.gender.data,
            # biography = form.biography.data,
            # profilePhoto = filename,
            request.form['first_name'],
            request.form['last_name'],
            request.form['email'],
            request.form['location'],
            request.form['gender'],
            request.form['biography'],
            filename,
            created_on=datetime.now().strftime("%B %d, %Y"))
        db.session.add(newUser)
        db.session.commit()
        flash('You have successfully added a new profile.', 'success')
        return redirect(url_for('profiles'))
    return render_template('profile.html', form=form)
コード例 #29
0
def add_profile():
    """Either (GET) provide profile form or (POST) create the profile"""
    form = ProfileForm()
    if form.validate_on_submit():
        # Get values from form
        fname = request.form['first_name']
        lname = request.form['last_name']
        gender = request.form['gender']
        email = request.form['email']
        location = request.form['location']
        bio = request.form['bio']

        try:
            """Idea for now: need to save the picture, and save the filename. Store items to database"""
            p_filename = save_photo(
                request.files['profile_picture'])  # profile photo filename
            profile = UserProfile(fname, lname, gender, email, location, bio,
                                  p_filename)
            db.session.add(profile)
            db.session.commit()
            flash('User successfully created', 'success')
            return redirect(url_for('view_profiles'))
        except:
            flash("User could not be created", 'danger')
    return render_template('add_profile.html', form=form)
コード例 #30
0
def account_settings():
    '''账户设置,包括改密码等'''
    user = current_user
    form = ProfileForm(formdata=request.form, obj=user)
    errors = []
    if form.validate_on_submit():
        username = form['username'].data.strip()
        if username == user.username:
            pass
        elif User.query.filter_by(username=username).all():
            errors.append(
                _("Sorry, the username " + username + " has been taken!"))
        else:
            user.username = username

        user.homepage = form['homepage'].data.strip()
        if not user.homepage.startswith('http'):
            user.homepage = 'http://' + user.homepage
        user.description = form['description'].data.strip()
        if request.files.get('avatar'):
            avatar = request.files['avatar']
            ok, info = handle_upload(avatar, 'image')
            if ok:
                user.set_avatar(resize_avatar(info))
            else:
                errors.append(_("Avatar upload failed"))
        user.save()
    return render_template('settings.html',
                           user=user,
                           form=form,
                           errors=errors)
コード例 #31
0
ファイル: admin.py プロジェクト: Lovemma/Gatsby
def profile():
    form = ProfileForm(CombinedMultiDict((request.files, request.form)))
    if request.method == 'POST':
        avatar_path = ''
        if form.validate():
            image = form.avatar.data
            intro = form.intro.data
            github_url = form.github_url.data
            linkedin_url = form.linkedin_url.data
            avatar_path = secure_filename(image.filename)
            uploaded_file = Path(
                current_app.config.get('UPLOAD_FOLDER')) / avatar_path
            image.save(str(uploaded_file))
            form.avatar_path.data = avatar_path
            kw = {
                'intro': intro,
                'github_url': github_url,
                'linkedin_url': linkedin_url
            }
            if avatar_path:
                kw.update(avatar=avatar_path)
            set_profile(**kw)
        if not avatar_path:
            form.avatar_path.data = get_profile().avatar

    elif request.method == 'GET':
        profile = get_profile()
        form.intro.data = profile.intro
        form.github_url.data = profile.github_url
        form.avatar_path.data = profile.avatar

    return render_template('admin/profile.html', form=form)
コード例 #32
0
def profile():
    form = ProfileForm()

    if form.validate_on_submit():
        current_user.email = form.email.data
        current_user.telefone = form.telefone.data
        current_user.sobremim = form.sobremim.data
        current_user.registro = form.registro.data
        current_user.ifcomunity = form.ifcomunity.data
        current_user.sobrenome = form.sobrenome.data
        current_user.username = form.username.data
        current_user.base = form.base.data
        current_user.pais = form.pais.data

        db.session.add(current_user)
        db.session.commit()

        flash("dados alterados com sucesso", "success")
        return redirect(url_for(".profile"))

    form.email.data = current_user.email
    form.telefone.data = current_user.telefone
    form.sobremim.data = current_user.sobremim
    form.registro.data = current_user.registro
    form.ifcomunity.data = current_user.ifcomunity
    form.sobrenome.data = current_user.sobrenome
    form.username.data = current_user.username
    form.base.data = current_user.base
    form.pais.data = current_user.pais

    return render_template("user/profile/edit.html", form=form)
コード例 #33
0
ファイル: profile.py プロジェクト: LRCP/nutrition
def profile_post():
    form = ProfileForm(request.form)
    #print request.form

    if form.validate():

        #get the user from the database session
        user = current_user
        # do not store the results of calculations using variable defined in
        # models.py That is what models.py is for.
        user.calorie_goal = form.calorie_goal.data
        user.protein_goal = form.protein_goal.data
        #what about user.amino_acid_goals?
        #Institute of Medicine's Food and Nutrition Board
        # Essential Amino Acid    Needed per g of Protein Needed for 50g of Protein
        #     Trytophan   7mg/.007g   .35g
        #     Threonine   27mg/.027g  1.35g
        #     Isoleucine  25mg/025g   1.25g
        #     Leucine 55mg/.055g  2.76g
        #     Lysine  51mg/.051g  2.56g
        #     Methionine+Cystine  25mg/.025g  1.25g
        #     Phenylalanine+Tyrosine  47mg/.047g  2.36g
        #     Valine  32mg/.032g  1.60g
        #     Histidine   18mg/.018g  .90g
        #age of user determines multiplier of x times kg of weight
        # 1.5g per kg - infants
        # 1.1g per kg - 1-3 years
        # .95g per kg - 4-13 years
        # .85g per kg - 14-18 years
        # .80g per kg - adults
        # 1.1g per kg - pregnant and lactating women

        user.carbohydrate_goal = form.carbohydrate_goal.data
        user.fat_goal = form.fat_goal.data
        #user.nutrient_goal = form.nutrient_goal.data
        user.birthday = form.birthday.data
        user.set_weight(form.weight.data, form.weight_unit.data)
        #user.set_weight_goal(form.weight_goal.data, form.weight_unit.data)
        user.set_height(form.height_in_centimeters.data / 100)
        user.gender = form.gender.data
        user.activity_level = form.activity_level.data
        user.set_weekly_weight_change(form.weekly_change_level.data)
        session.commit()
        #Here we need to save the information enterred by the User.
        #need access to the user object.
        #return redirect(url_for('profile_get'))

        flash("You have successfully enterred your Profile Information.")
        flash("Select Foodlog to continue.")
        return render_template(
            'profile.html',
            title='Profile',
            form=form,
            text=
            'Either stay on your Profile or go to the Home, Foodlog or Logout Page.',
        )
    else:
        flash("Try again")
        print form.errors
        return render_template('profile.html', title='Profile', form=form)
コード例 #34
0
ファイル: views.py プロジェクト: ReginaZaripova/diplom
def create_profile():
        form = ProfileForm()
        if request.method == 'POST' and form.validate_on_submit():
            new_data = User.query.get(str(id))
            new_data.email = form.email.data
            db.session.commit()
            return redirect('/index')
        return render_template('create_profile.html', form=form)
コード例 #35
0
ファイル: user.py プロジェクト: lu-zero/plaid
def settings():
    form = ProfileForm(request.form, current_user)
    if request.method == 'POST' and form.validate():
        form.populate_obj(current_user)
        current_user.password = encrypt_password(current_user.password)
        db.session.commit()
        return redirect('/')
    else:
        return render_template('profile.html', form=form, profile=current_user)
コード例 #36
0
ファイル: views.py プロジェクト: StreetVoice/ididit
def settings(request):
    form = ProfileForm(request.POST or None, request.FILES or None, instance=request.user.profile)
    if form.is_valid():
        profile = form.save(commit=False)
        profile.user = request.user
        profile.save()

        return redirect('/dashboard/')

    return render(request, 'settings.html', {'form': form})
コード例 #37
0
ファイル: views.py プロジェクト: simonv3/ideas
def profile(request):
    user = request.user
    your_ideas = Idea.objects.filter(user = user).order_by('-date')
    ideas_len = len(your_ideas)
    your_slates = Slate.objects.filter(creator = user).order_by('-id')
    slates_len = len(your_slates)
    if request.method == 'POST': #If something has been submitted
            print "post"
            if 'vote' in request.POST:
                voteForm = VoteForm(request.POST)
                if voteForm.is_valid():
                    helpers.vote(voteForm,request.user)
            if 'profile' in request.POST:
                print "profile"
                profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.get_profile())
                print profile_form
                if profile_form.is_valid():
                    print "valid"
                    photo_string = hashlib.sha224(
                            "profile_pic"+
                            CLIENT_SUB_DOMAIN+
                            str(user.id)).hexdigest()
                    write_url = '%susers/%s.png' %(STATIC_DOC_ROOT,photo_string)
                    print photo_string
                    try:
                        photo = request.FILES['photo']
                    except:#no image
                        pass
                    else:
                        success, string = helpers.handle_uploaded_file(photo, write_url, "profile")
                        if success:
                            print success
                            user.get_profile().photo = photo_string + ".png"
                            user.get_profile().save()
                        else:

                            messages.error(request, "That file was too large.")
                        user.save()
                        return HttpResponseRedirect("/accounts/profile/")



    profile_form = ProfileForm()

    voted_on = Vote.objects.filter(user = user)
    voted_len = len(voted_on)
    commented_on = user.get_profile().get_ideas_commented_on()
    comments_len = len(commented_on)

    return render_to_response('main/profile.html', locals(), context_instance=RequestContext(request))
コード例 #38
0
ファイル: user.py プロジェクト: Aaron1992/ustc-course
def account_settings():
    '''账户设置,包括改密码等'''
    user = current_user
    form = ProfileForm(request.form, user)
    if form.validate_on_submit():
        #user.username = form['username'].data
        #user.gender = form['gender'].data
        user.homepage = form['homepage'].data.strip()
        if not user.homepage.startswith('http'):
            user.homepage = 'http://' + user.homepage
        user.description = form['description'].data.strip()
        if request.files.get('avatar'):
            avatar = request.files['avatar']
            ok,info = handle_upload(avatar,'image')
            if ok:
                user.set_avatar(info)
            else:
                errors.append(_("Avatar upload failed"))
        user.save()
    return render_template('settings.html', user=user, form=form)
コード例 #39
0
ファイル: views.py プロジェクト: yelangchs/operator_system
def edit_profile():
    form = ProfileForm()
    if form.validate_on_submit():
        username = form.username.data
        email = form.email.data
        alarm_email = form.alarm_email.data
        try:
            g.user.username = username
            g.user.email = email
            g.user.alarm_email = alarm_email
            db.session.commit()
            return redirect(url_for('index'))

        except (InvalidRequestError, IntegrityError):
            flash('Duplicate username!')
            db.session.rollback()

    form.username.data = g.user.username
    form.email.data = g.user.email
    form.alarm_email.data = g.user.alarm_email
    return render_template('edit_profile.html', form=form)
コード例 #40
0
ファイル: views.py プロジェクト: meharig/dsahlkhafklhakl-aon
def edit_profile_view(request):
    user_name = request.user.username
    if request.method == 'GET':
        num_notifications = get_notifications(request)
        user = get_object_or_404(User, username=user_name)
        profile = get_object_or_404(UserProfile, user=user)
        user_skills = profile.skills.all()
        user_requests = Request.objects.filter(created_by=user)[:5]
        user_offers = Offer.objects.filter(offer_by=user, is_accepted=True)[:5]
        requests_count = len(user_requests)
        offers_count = len(user_offers)
        data = {'profile': profile,
                'skills': user_skills,
                'offers': user_offers,
                'requests': user_requests,
                'num_offers': offers_count,
                'num_requests': requests_count,
                }
        return render(request=request, template_name='app/editProfile.html',
                      context={'data': data, 'num_notifications': num_notifications})

    elif request.method == 'POST':
        instance = get_object_or_404(UserProfile, user=request.user)
        form = ProfileForm(request.POST or None, instance=instance)
        if form.is_valid():
            for id in request.POST.getlist('skills'):
                tag = SkillTag.objects.get(pk=id)
                if tag:
                    instance.skills.add(tag)

            instance.save()
            form.save(commit=True)
            messages.add_message(request, messages.SUCCESS, 'Your Profile Updated Successfully !')
            return HttpResponseRedirect('/users/' + str(user_name))

        else:
            return HttpResponseRedirect("/users/" + str(user_name))
コード例 #41
0
ファイル: views.py プロジェクト: ThinkZ/pkyx
def profile_edit():
    user = User.find_by_id(bson_obj_id(current_user.id))
    if not user:
        abort(404)
    form = ProfileForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            username = form.username.data
            location = form.location.data
            website = form.website.data
            introduction = form.introduction.data
            data = {
                'username': username,
                'location': location,
                'website': website,
                'introduction': introduction
            }

            avatar = request.files['avatar']
            if avatar and AllowFile.is_img(avatar.filename):
                filename = secure_filename(avatar.filename)
                fs = GridFS(mongo.db, collection="avatar")
                avatar_id = fs.put(avatar, content_type=avatar.content_type, filename=filename)
                if avatar_id:
                    if user['avatar']:
                        fs.delete(bson_obj_id(user['avatar']))
                    data['avatar'] = avatar_id
            else:
                flash('图片格式不支持', 'red')

            User.update_user(user['_id'], data)

            return redirect(url_for('.profile'))
        else:
            flash('资料修改失败', 'red')
    return render_template('profile_edit.html', user=user, form=form, title='编辑资料')
コード例 #42
0
ファイル: profile.py プロジェクト: mrojass/nutrition
def profile_post():
    form = ProfileForm(request.form)
    #print request.form


    if form.validate():

        #get the user from the database session
        user = current_user
        # do not store the results of calculations using variable defined in
        # models.py That is what models.py is for.
        user.calorie_goal = form.calorie_goal.data
        user.protein_goal = form.protein_goal.data
        #what about user.amino_acid_goals?
        #Institute of Medicine's Food and Nutrition Board
        # Essential Amino Acid    Needed per g of Protein Needed for 50g of Protein
        #     Trytophan   7mg/.007g   .35g
        #     Threonine   27mg/.027g  1.35g
        #     Isoleucine  25mg/025g   1.25g
        #     Leucine 55mg/.055g  2.76g
        #     Lysine  51mg/.051g  2.56g
        #     Methionine+Cystine  25mg/.025g  1.25g
        #     Phenylalanine+Tyrosine  47mg/.047g  2.36g
        #     Valine  32mg/.032g  1.60g
        #     Histidine   18mg/.018g  .90g
        #age of user determines multiplier of x times kg of weight
        # 1.5g per kg - infants
        # 1.1g per kg - 1-3 years
        # .95g per kg - 4-13 years
        # .85g per kg - 14-18 years
        # .80g per kg - adults
        # 1.1g per kg - pregnant and lactating women

        user.carbohydrate_goal = form.carbohydrate_goal.data
        user.fat_goal = form.fat_goal.data
        #user.nutrient_goal = form.nutrient_goal.data
        user.birthday = form.birthday.data
        user.set_weight(form.weight.data, form.weight_unit.data)
        #user.set_weight_goal(form.weight_goal.data, form.weight_unit.data)
        user.set_height(form.height_in_centimeters.data / 100)
        user.gender = form.gender.data 
        user.activity_level = form.activity_level.data
        user.set_weekly_weight_change(form.weekly_change_level.data)
        session.commit()
        #Here we need to save the information enterred by the User.
        #need access to the user object.
        #return redirect(url_for('profile_get'))

        flash("You have successfully enterred your Profile Information.")
        flash("Select Foodlog to continue.")
        return render_template(
            'profile.html',
            title='Profile',
            form=form,
            text='Either stay on your Profile or go to the Home, Foodlog or Logout Page.',

            )
    else:
        flash("Try again")
        print form.errors
        return render_template(
            'profile.html',
            title='Profile',
            form=form)