Example #1
0
def edit_user():
    """Process profile edit. On successful submit, redirects to
    profile page with flashed message. Or shows form."""

    if not g.user:
        flash(NOT_LOGGED_IN_MSG)
        return redirect('/login')

    user = User.query.get(session[CURR_USER_KEY])

    form = ProfileEditForm(obj=user)

    if form.validate_on_submit():
        user.first_name = form.first_name.data
        user.last_name = form.last_name.data
        user.description = form.description.data
        user.email = form.email.data
        user.image_url = form.image_url.data

        db.session.commit()
        flash("Profile edited.", "success")
        return redirect("/profile")

    else:
        return render_template("/profile/edit-form.html", form=form)
Example #2
0
def admin_edit_profile(request, username):
	msg, msg_type = "", ""
	if request.user.is_authenticated():
		# Gets profile of the current user logged in the system
		adminprofile = UserProfile.objects.get(pk=request.user.id)
		# Checks if the user trying to edit a profile is an admin
		if adminprofile.role == 'admin':
			user = User.objects.get(username=username)
			userprofile = UserProfile.objects.get(pk=user.id)
			if request.method == 'POST':
				form = ProfileEditForm(request.POST, instance=userprofile)
				if form.is_valid():
					form.save()
					return HttpResponseRedirect('/admin/users/' + username + '/profile/?edit=success')
			else:
				form = ProfileEditForm(instance=userprofile)
			if request.GET and "edit" in request.GET:
				msg_type = request.GET["edit"]
				if msg_type == "success":
					msg = "User profile edited successfully"
				elif msg_type == "error":
					msg = "An error occurred when editing the user profile."
			return render_to_response("admin_edit_profile.html", {"form": form, "message": msg, "message_type": msg_type,  "notifications": UserProfile.objects.get(user=request.user).notifications.all()[:5], "read_notifications": UserProfile.objects.get(user=request.user).read_notifications.all()[:5]}, context_instance=RequestContext(request))
		else:
			return HttpResponse('You do not have permission to access the page requested.')
Example #3
0
def edit_profile():
    """ GET: show profile edit form, POST: updates user profile """
    if not g.user:
        flash(NOT_LOGGED_IN_MSG)
        return redirect('/login')

    form = ProfileEditForm(obj=g.user)

    if form.validate_on_submit():
        first_name = form.first_name.data
        last_name = form.last_name.data
        description = form.description.data
        email = form.email.data
        image_url = form.image_url.data

        g.user.first_name = first_name
        g.user.last_name = last_name
        g.user.description = description
        g.user.email = email
        g.user.image_url = image_url

        db.session.commit()

        flash('Profile edited.')
        return redirect('/profile')

    else:
        return render_template('profile/edit-form.html', form=form)
Example #4
0
def profile():
    if not logged():
        return redirect('/init/login')
    user = User.query.filter_by(login=session['login']).first()

    form = ProfileEditForm()
    if form.validate_on_submit():
        if form.delete_account.data:
            db.session.delete(user)
            db.session.commit()
            return redirect('/init/register')
        elif form.submit.data:
            users = [i for i in User.query.all()]
            for i in range(len(users)):
                if users[i].id == user.id:
                    del users[i]
                    break
            users = {i.login for i in users}

            if form.login.data in users:
                return redirect('/profile')
            user.login = form.login.data
            if form.old_password.data and form.new_password.data:
                if password_exists(user.password_hash, form.old_password.data):
                    user.password_hash = to_hash(form.new_password.data)
            db.session.commit()
            session['login'] = user.login
            return redirect('/index')

    form.login.data = user.login
    return render_template('profile.html', user=user, form=form)
Example #5
0
def profile():
    """Update profile for current user."""

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    user = g.user
    form = ProfileEditForm(obj=user)

    if form.validate_on_submit():
        if User.authenticate(user.username, form.password.data):
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data or "/static/images/default-pic.png"
            user.header_image_url = form.header_image_url.data or "/static/images/warbler-hero.jpg"
            user.bio = form.bio.data
            user.location = form.location.data

            db.session.commit()
            return redirect(f"/users/{user.id}")

        flash("Wrong password, please try again.", 'danger')

    return render_template('users/edit.html', form=form, user_id=user.id)
Example #6
0
def profile(request):
    if request.method == 'POST':
        form = ProfileEditForm(request.POST)
        if form.is_valid():
            user = request.user
            userinfo = user.userinfo
            user.first_name = form.cleaned_data['first_name']
            user.last_name = form.cleaned_data['last_name']
            userinfo.phone = form.cleaned_data['phone']
            userinfo.skype = form.cleaned_data['skype']
            userinfo.save()
            user.save()
            request.session['alert'] = _('Profile has been successfully edited')
            return HttpResponseRedirect(reverse('profile'))
    else:
        user = request.user
        data = {'first_name': user.first_name,
                'last_name': user.last_name,
                'phone': user.userinfo.phone,
                'skype': user.userinfo.skype}
        form = ProfileEditForm(data)
    context = {}
    context.update(csrf(request))
    context['form'] = form
    return render(request, 'profile.html', context)
Example #7
0
def profile():
    """Update profile for current user."""
    if not g.user:
        flash('Access unauthorized.', 'danger')
        return redirect('/')
    form = ProfileEditForm(obj=g.user)
    if form.validate_on_submit():
        user = User.authenticate(g.user.username, form.password.data)
        if user:
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data or User.image_url.default.arg
            user.header_image_url = form.header_image_url.data or User.header_image_url.default.arg
            user.bio = form.bio.data
            try:
                db.session.commit()
            except IntegrityError:
                flash('Username taken!', 'danger')
                redirect('/users/profile')
            flash('Updated Successfully', 'success')
            return redirect(f'/users/{user.id}')
        else:
            flash('Invalid credentials', 'danger')
            return redirect('/')
    else:
        return render_template('/users/edit.html', form=form)
Example #8
0
def edit_profile(request):
	if request.user.is_authenticated():
		# Gets profile of the current user logged in the system
		profile = UserProfile.objects.get(pk=request.user.id)
		if request.method == 'POST':
			form = ProfileEditForm(request.POST, instance=profile)
			if form.is_valid():
				form.save()
				return HttpResponseRedirect('/')
		else:
			form = ProfileEditForm(instance=profile)
		return render_to_response("profile.html", {"form": form, "user": request.user,  "notifications": UserProfile.objects.get(user=request.user).notifications.all()[:5], "read_notifications": UserProfile.objects.get(user=request.user).read_notifications.all()[:5]}, context_instance=RequestContext(request))
Example #9
0
def profile_edit(request):
    if request.method == 'POST':
        form = ProfileEditForm(request.user.username, request.POST,
            instance=request.user)
        if form.is_valid():
            form.save()
            messages.info(request, "Your profile was saved")
            logger.info("User %s saved his profile" % request.user)
            return HttpResponseRedirect(reverse('profile-edit'))
    else:
        form = ProfileEditForm(request.user.username, instance=request.user)

    return render_to_response('people/profile-edit.html', {'form': form},
        RequestContext(request))
Example #10
0
def edit(request):
    try:
        profile = request.user.get_profile()
    except ObjectDoesNotExist:
        profile = Profile.objects.create(user=request.user)
    if request.method == 'POST':
        form = ProfileEditForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            try:          
                form.save()
            except:
                return HttpResponse('save failed!')
            return HttpResponseRedirect('/home/')
    else:
        form = ProfileEditForm(instance=profile)
    return render_to_response('profile/edit.html', {'form': form, },
                              context_instance=RequestContext(request))
Example #11
0
def profile_edit_page(user_id):
    searchform = SearchForm()
    db = current_app.config["db"]
    user = db.get_user_by_id(user_id)
    if user is None:
        abort(404)
    if not current_user.id == user_id:
        abort(401)
    form = ProfileEditForm()
    if form.validate_on_submit():
        username = form.data["username"]
        email = form.data["email"]
        password = None
        gender = form.data["gender"]
        if form.data["old_password"]:
            password = hasher.hash(form.data["new_password"])
        profile_picture = form.data["profile_picture"]
        filename = None
        if profile_picture:
            filename = secure_filename(profile_picture.filename)
            _, f_ext = os.path.splitext(filename)
            filename = username + f_ext
            profile_picture.save(
                os.path.join(current_app.root_path, 'static/profile_pictures',
                             filename))
        new_user = User(username=username,
                        email=email,
                        password=password,
                        profile_picture=filename,
                        gender=gender)
        if (form.data["old_password"] and hasher.verify(
                form.data["old_password"],
                user.password)) or (not form.data["old_password"]
                                    and not form.data["new_password"]):
            db.update_user(user_id, new_user)
            flash("User information updated successfully.")
            return redirect(url_for("profile_page", user_id=user_id))
        else:
            flash("Old password is wrong.")
    form.username.data = user.username
    form.email.data = user.email
    form.gender.data = user.gender if user.gender else ""
    return render_template("register.html",
                           form=form,
                           edit_profile=True,
                           searchform=searchform)
Example #12
0
def profile():
    """Update profile for current user."""

    form = ProfileEditForm()
    if form.validate_on_submit():
        if User.authenticate(g.user.username, form.password.data) is not False:
            g.user.username = form.username.data
            g.user.email = form.email.data
            g.user.image_url = form.image_url.data
            g.user.header_image_url = form.header_image_url.data
            g.user.bio = form.bio.data
            db.session.add(g.user)
            db.session.commit()
            flash("Profile successfully updated")
            return redirect(f"/users/{g.user.id}")
        else:
            flash("Incorrect password")
    return render_template("users/edit.html", form=form)
Example #13
0
def edit_profile():
    form = ProfileEditForm()
    if form.validate_on_submit():
        hint = form.hint.data
        address = form.address.data
        first_name = form.first_name.data
        last_name = form.last_name.data
        current_user.hint = hint
        current_user.address = address
        current_user.first_name = first_name
        current_user.last_name = last_name

        current_user.save_to_db(db)

        return redirect("/profile")
    hint = current_user.hint
    address = current_user.address
    return render_template("edit_profile.html",
                           form=form,
                           hint=hint,
                           address=address)
Example #14
0
def edit_user():
    """If user logged in, show and process form for editing user information.
    Otherwise, send to login page.
    """
    if CURR_USER_KEY in session:
        user = g.user
        form = ProfileEditForm(obj=user)

        if form.validate_on_submit():
            user.first_name = form.first_name.data
            user.last_name = form.last_name.data
            user.description = form.description.data
            user.email = form.email.data
            user.image_url = form.image_url.data or "/static/images/default-pic.png"

            db.session.commit()

            flash("Profile edited.")
            return redirect("/profile")

        return render_template('/profile/edit-form.html', form=form)
    else:
        return redirect('/login')
Example #15
0
def profile():
    """Update profile for current user."""

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    form = ProfileEditForm()

    if form.validate_on_submit():
        user = User.authenticate(g.user.username, form.password.data)

        if user:
            for field in (f for f in form if f.widget.input_type != 'hidden'
                          and f.name != 'password'):
                val = field.data
                colDefault = getattr(User, field.name).default
                # If no value was input and a default value is available, use the default, otherwise use the input (even if blank)
                setattr(user, field.name,
                        colDefault.arg if not val and colDefault else val)

            db.session.commit()
            return redirect(f"/users/{g.user.id}")

        flash("Incorrect password.", 'danger')

    # Set form data for fields that have it, or that is a holdover from a failed submission
    for field in (f for f in form
                  if f.widget.input_type != 'hidden' and not f.data):
        val = getattr(g.user, field.name)
        colDefault = getattr(User, field.name).default
        # If no column default is defined, display the data
        # If a default is defined, only display the data if the current value differs
        if not colDefault or val != colDefault.arg:
            field.data = val

    return render_template('users/edit.html', form=form, user_id=g.user.id)
Example #16
0
def profile_edit(request):
    if request.method == 'POST':
        form = ProfileEditForm(request.user.username,
                               request.POST,
                               instance=request.user)
        if form.is_valid():
            form.save()
            messages.info(request, "Your profile was saved")
            logger.info("User %s saved his profile" % request.user)
            return HttpResponseRedirect(reverse('profile-edit'))
    else:
        form = ProfileEditForm(request.user.username, instance=request.user)

    return render_to_response('people/profile-edit.html', {'form': form},
                              RequestContext(request))