コード例 #1
0
def put_user(user_id):
    db_user = db.session.query(Users).get(user_id)
    if db_user is None:
        return render_template(
            'user/list.html',
            users=db.session.query(Users).order_by(Users.id).all(),
            errors=u'Пользователя с id=%s не существует' % user_id)
    db_roles = db.session.query(Roles).all()
    radio_roles = [(role.id, role.name) for role in db_roles]
    form = EditUserForm(login=db_user.login)
    form.role.choices = radio_roles
    if form.validate_on_submit():
        password = form.password.data.strip()
        if password:
            user = User(form.login.data.strip(), form.password.data.strip())
            db_user.password = user.pw_hash
        else:
            user = User(form.login.data.strip())

        if db_user.login != user.login and db.session.query(Users).filter(
                Users.login == user.login).count() > 0:
            return render_template(
                'user/edit.html',
                errors=[
                    u'Пользователь с логином <b>%s</b> уже существует' %
                    user.login
                ],
                form=form)
        db_user.login = user.login
        db_role = db.session.query(Roles).get(form.role.data)
        db_user.roles[0] = db_role
        db.session.commit()
        flash(u'Пользователь изменен')
        return redirect(url_for('users'))
    return render_template('user/edit.html', form=form, user=db_user)
コード例 #2
0
def profile():
    """Update profile for current user."""

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

    # username, password
    # print('***********g.user.id', g.user.id)
    user = User.query.get_or_404(g.user.id)

    form = EditUserForm(obj=user)

    user = User.authenticate(user.username, form.password.data)

    if user and form.validate_on_submit():
        user.username = form.username.data
        user.email = form.email.data
        user.image_url = form.image_url.data
        user.header_image_url = form.header_image_url.data
        user.bio = form.bio.data

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

    else:
        return render_template('users/edit.html', form=form)
コード例 #3
0
    def put(self, id):
        user = User.get_by_id(id)

        if user is None or not user.can_edit():
            flash(gettext('The user was not found'), 'error')
            return redirect(url_for('UsersView:index'))

        if request.method in ['POST']:
            form = EditUserForm()
            if form.validate_on_submit():
                if form.password.data:
                    user.set_password(form.password.data)
                del form.password
                form.populate_obj(user)
                user.save()
                refresh()
                return resp(url_for('UsersView:get', id=user.id), redirect=True,
                            message=gettext('User was succesfully updated'))
            else:
                return resp('admin/users/edit.html', form=form, user=user,
                            message=gettext('Invalid submission, please check the messages below'))
        else:
            form = EditUserForm(user=user)

        return resp('admin/users/edit.html', form=form, user=user)
コード例 #4
0
ファイル: views.py プロジェクト: nirajbhutada/julython.org
def edit_profile(request, username, template_name="people/edit.html"):
    from forms import EditUserForm

    user = request.user

    if user.username != request.user.username:
        http403 = HttpResponse("This ain't you!")
        http403.status = 403
        return http403

    form = EditUserForm(request.POST or None, user=request.user)

    if form.is_valid():
        for key, value in form.cleaned_data.iteritems():
            if key in ["gittip"]:
                continue
            if key in ["email"]:
                # send verification email
                domain = get_current_site(request).domain
                if value is not None:
                    send_verify_email(value, user.pk, domain)
                # Don't actually add email to user model.
                continue
            if key == "team":
                # slugify the team to allow easy lookups
                setattr(user, "team_slug", slugify(value))
            setattr(user, key, value)
        user.save()

        return HttpResponseRedirect(reverse("member-profile", kwargs={"username": user.username}))

    ctx = {"form": form, "profile": user, "active": "edit"}
    return render(request, template_name, ctx, context_instance=RequestContext(request))
コード例 #5
0
ファイル: app.py プロジェクト: puglisac/warbler
def profile(id):
    """Update profile for current user."""

    # IMPLEMENT THIS
    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    user = User.query.get_or_404(id)
    form = EditUserForm(obj=user)

    if form.validate_on_submit():
        """handles password submission"""
        password = User.authenticate(user.username, form.password.data)
        if password or g.user.is_admin:
            """updates the user profile"""
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data
            user.header_image_url = form.header_image_url.data
            user.bio = form.bio.data
            user.is_admin = form.is_admin.data
            db.session.add(user)
            db.session.commit()
            flash("Updated Profile", "success")
            return redirect(f"/users/{user.id}")
        else:
            """shows for invalid password"""
            flash("Invalid Password", "danger")
            return redirect(f"/users/{user.id}/profile")
    else:
        return render_template("users/edit.html", user=user, form=form)
コード例 #6
0
def user_edit_page(user_id):

    if not current_user.key.id() == user_id:
        if not current_user.is_admin():
            return render_template('not_found_page.html'), 404

    user = User.get_by_id(str(user_id).lower())

    if user:

        form = EditUserForm()
        checked_status = 'checked' if user.is_admin() else ''

        if form.validate_on_submit():

            user.name = form.name.data

            if current_user.is_admin():
                user.isAdmin = form.isAdmin.data

            user.put()

            return redirect(url_for('web_app.user_edit_page', user_id=user_id))

        return render_template('edit_user_page.html',
                               form=form,
                               checked_status=checked_status,
                               user=user)

    else:
        return render_template('not_found_page.html'), 404
コード例 #7
0
def edit_user():
    #check if the id is a digit
    if request.args.get('id').isdigit():
        form = EditUserForm(request.form)
        #convert to digit
        user_id = request.args.get('id').encode('ascii', 'ignore')
        #get user and the number of submitted documents
        result = db.session.query(User, func.count(
            Submit.uid)).outerjoin(Submit).filter(User.id == user_id).group_by(
                Submit.uid).first()
        if result:
            user = result[0]
            docs = result[1]
            if request.method == 'GET':
                form = EditUserForm(request.form,
                                    first=user.first,
                                    last=user.last,
                                    phone=user.phone,
                                    email=user.email)
            #update db on form submit
            elif form.validate_on_submit():
                user.first = form.first.data
                user.last = form.last.data
                user.phone = form.phone.data
                user.email = form.email.data
                db.session.commit()
                return redirect(url_for('users'))
            return render_template('edit_user.html',
                                   form=form,
                                   user=user,
                                   docs=docs,
                                   current_user=current_user)
    abort(404)
コード例 #8
0
ファイル: views.py プロジェクト: florinmatei/julython.org
def edit_profile(request, username, template_name='people/edit.html'):
    from forms import EditUserForm
    user = User.get_by_auth_id('twitter:%s' % username)

    if user == None:
        raise Http404("User not found")
    
    if user.key != request.user.key:
        http403 = HttpResponse("This ain't you!")
        http403.status = 403
        return http403
    

    form = EditUserForm(request.POST or None, user=request.user)
    if form.is_valid():
        for key in form.cleaned_data:
            if key == 'email':
                continue
            setattr(user, key, form.cleaned_data.get(key))
        slugify(user.location)
        user.put()
        return HttpResponseRedirect(
            reverse('member-profile', 
                    kwargs={'username':request.user.username}
                   )
        )
        
    

    return render_to_response(template_name, 
        {'form':form}, 
        context_instance=RequestContext(request))
コード例 #9
0
ファイル: app.py プロジェクト: JchanCode/Warbler
def profile():
    """Update profile for current user."""

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

    form = EditUserForm()

    if form.validate_on_submit():
        if User.check_entered_pwd(g.user.password, form.password.data):
            user = User.query.get(g.user.id)

            user.username = form.username.data
            user.email = form.email.data
            user.password = form.password.data
            user.image_url = form.image_url.data
            user.header_image_url = form.header_url.data
            user.bio = form.bio.data
            user.location = form.location.data

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

            flash("Info Edited", "success")
            return redirect(f"{g.user.id}")
        else:
            flash("Wrong Password", "danger")
            return redirect("/")

    return render_template("users/edit.html", form=form)
コード例 #10
0
def profile():
    """Update profile for current user."""

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    user = User.query.get_or_404(session[CURR_USER_KEY])
    form = EditUserForm(obj = user)

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

        if is_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
            db.session.commit()
            flash('Updated user successfully!', 'success')
            return redirect(f'/users/{user.id}')

        else:
            flash('Incorrect Password! Cannot edit user!', 'danger')
            return redirect('/')


    return render_template('users/edit.html', form=form, user = user)
コード例 #11
0
ファイル: app.py プロジェクト: mfierro31/warbler
def edit_user(user_id):
    """Edit user profile if POST request, show edit user form if GET request"""
    user = User.query.get_or_404(user_id)

    form = EditUserForm(obj=user)

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

            if form.email.data:
                user.email = form.email.data

            if form.image_url.data:
                user.image_url = form.image_url.data

            if form.header_image_url.data:
                user.header_image_url = form.header_image_url.data

            if form.bio.data:
                user.bio = form.bio.data

            db.session.commit()

            flash('Successfully saved changes!', 'success')
            return redirect(f'/users/{user.id}')
        else:
            flash(
                "Sorry, that's not the correct password for your account.  Please type in another password.",
                "danger")
            return redirect(f'/users/{user.id}/edit')
    else:
        return render_template('users/edit.html', user=user, form=form)
コード例 #12
0
def post_user():
    # create a new user
    db_roles = db.session.query(Roles).all()
    radio_roles = [(role.id, role.name) for role in db_roles]
    form = EditUserForm()
    form.role.choices = radio_roles
    if form.validate_on_submit():
        user = User(form.login.data.strip(), form.password.data.strip())
        if db.session.query(Users).filter(
                Users.login == user.login).count() > 0:
            return render_template(
                'user/edit.html',
                errors=[
                    u'Пользователь с логином <b>%s</b> уже существует' %
                    user.login
                ],
                form=form)
        db_user = Users(user.login, user.pw_hash)
        db_role = db.session.query(Roles).get(form.role.data)
        db_user.roles.append(db_role)
        db.session.add(db_user)
        db.session.commit()
        flash(u'Пользователь добавлен')
        return redirect(url_for('users'))
    return render_template('user/edit.html', form=form)
コード例 #13
0
def edit_profile():
    """Update profile for current user."""

    # IMPLEMENT THIS

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

    user = g.user
    form = EditUserForm(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

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

        flash(f"{user.username}, password doesn't match! please try again.",
              'danger')

    return render_template('users/edit.html', form=form, user_id=user.id)
コード例 #14
0
ファイル: app.py プロジェクト: jake202020/goutdoors
def edit_user(username):
    """Show form for editing user details (GET) or add user edits to db and go to user page (POST)
    
    User cannot change username or password for now"""

    # Check if logged in user is this user
    if is_correct_user(username):
        form = EditUserForm(first_name=current_user.first_name,
                            last_name=current_user.last_name,
                            state_code=current_user.state_code)

        if form.validate_on_submit():
            current_user.first_name = form.first_name.data
            current_user.last_name = form.last_name.data
            current_user.state_code = form.state_code.data

            db.session.commit()

            flash("User updated")
            # on successful edit, redirect to users page
            return redirect(f"/users/{ current_user.username }")

        return render_template("edit_user.html", form=form)

    flash("Not your profile")
    return redirect("/")
コード例 #15
0
ファイル: app.py プロジェクト: calvinhla/wanderlust
def edit_user(username):

    form = EditUserForm(obj=g.user)
    form.location.choices = country_choices
    if form.validate_on_submit():
        first_name = form.first_name.data
        last_name = form.last_name.data
        email = form.email.data
        image = form.image.data
        username = form.username.data
        location = form.location.data
        bio = form.bio.data
        if type(image) is str:
            user = g.user.edit_user(first_name, last_name, username, location,
                                    bio)
        else:
            url = add_profile_picture(username, image)
            user = g.user.edit_user(first_name, last_name, username, location,
                                    bio, url)

        if user:
            db.session.add(user)
            db.session.commit()
            return redirect(url_for('show_user', username=username))
        else:
            form.username.errors.append('Username has already been taken')
            return render_template('form.html', form=form)

    return render_template('form.html', form=form)
コード例 #16
0
ファイル: app.py プロジェクト: f-westergren/warbler
def profile():
    """Update profile for current user."""

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

    user = g.user

    form = EditUserForm(obj=user)

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

        if user:
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data
            user.header_image_url = form.header_image_url.data
            user.bio = form.bio.data
            db.session.commit()
            flash("User information updated!", "success")
            return redirect(f"/users/{g.user.id}")

        flash("Invalid credentials.", 'danger')
        return redirect(f"/users/{g.user.id}")

    return render_template('/users/edit.html', form=form)
コード例 #17
0
ファイル: app.py プロジェクト: jakejg/warbler
def profile():
    """Update profile for current user."""

    form = EditUserForm()

    if form.validate_on_submit():
        if User.authenticate(g.user.username, form.password.data):
            try:
                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 or "/static/images/warbler-hero.jpg"
                g.user.bio = form.bio.data
                db.session.add(g.user)
                db.session.commit()

            except IntegrityError:
                flash("Username already taken", 'danger')
                return redirect(url_for('profile'))

            flash("Changes Successful!", "success")
            return redirect(f"{g.user.id}")

        flash("Incorrect Password", "danger")
        return redirect(url_for('profile'))

    return render_template('users/edit.html', form=form)
コード例 #18
0
def edit_profile(user_id):
    """On submit update user information.
    
    If form not validated show edit user form.

    If password incorrect flash message.
    """
    form = EditUserForm()
    curr_user = User.query.get_or_404(user_id)
    if curr_user.id != g.user.id:
        flash('You can only edit your own profile.', 'danger')
        return redirect('/leagues')
    if form.validate_on_submit():
        user = User.authenticate(form.username.data, form.password.data)
        if user:
            curr_user.username = form.username.data
            curr_user.image_url = form.image_url.data
            db.session.commit()
        else:
            flash('Incorrect username or password', 'danger')
            return render_template('edit_user.html', form=form, user=curr_user)
        flash(f"Successfully Edited {curr_user.username}'s Profile", "success")
        return redirect('/leagues')
    else:
        return render_template('edit_user.html', form=form, user=curr_user)
コード例 #19
0
def update_profile():

    if 'id' not in session:
        flash("Access unauthorized", "danger")
        return redirect('/users/login')

    user = User.query.get_or_404(session['id'])
    
    username = user.username
    img = user.img

    form = EditUserForm(obj=user)
    
    if form.validate_on_submit():

        if len(form.username.data) == 0:
            user.username= user.username
        else:
            user.username=form.username.data

        if len(form.img.data) == 0:
            user.img = user.img
        else:
            user.img=form.img.data

        db.session.commit()
        flash('update sucessful')

        return redirect("/")
    else:
        return render_template("users/edit.html", form=form, user=user)
コード例 #20
0
ファイル: app.py プロジェクト: marcoh1012/warbler
def profile():
    """Update profile for current user."""

    # IMPLEMENT THIS
    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    form = EditUserForm(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
            user.header_image_url = form.header_image_url.data
            user.bio = form.bio.data
            # form.populate_obj(user)
            db.session.commit()
            flash('Profile Edited', "success")
            return redirect(f'/users/{user.id}')

        flash("Error Wrong Password.", 'danger')
        return redirect('/')

    return render_template('users/edit.html', form=form)
コード例 #21
0
ファイル: users.py プロジェクト: horsekitlin/QASystem
    def post(self):
        form = EditUserForm()
        if form.validate_on_submit():
            new_user = get_dict(request.form,
                    'account',
                    'pwd',
                    'name',
                    'skills',
                    'email')

            folder = '{}/{}'.format(app.config["UPLOAD_FOLDER"], new_user["account"])
            logo = request.files['logo']
            filename = secure_filename(logo.filename)
            new_user['logo']=logo.filename
            if isdir(folder) == False:
                try:
                    makedirs(folder)
                except OSError as exc:
                    if exc.errorno == errno.EXIST and path.isdir(folder):
                        pass
                    else:
                        raise
            logo.save(join(folder, filename))
            try:
                User(**new_user).save()
            except:
                ValidationError(message='DB insert Error')
                return render_template('users/create.html',
                    form=form)
            return redirect(url_for('users.login'))
        return render_template('users/create.html', form=form)
コード例 #22
0
ファイル: app.py プロジェクト: quinetopia/warbler
def profile():
    """Update profile for current user."""

    # IMPLEMENT THIS

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

    form = EditUserForm(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
            user.header_image = form.header_image_url.data
            user.bio = form.bio.data

            db.session.commit()
            return redirect(f"/users/{user.id}")
        else:
            flash("Invalid credentials.", 'danger')
            return redirect('/')
    return render_template(
        "users/edit.html",
        form=form,
    )
コード例 #23
0
ファイル: app.py プロジェクト: comptonjon/cardboard_gm
def edit_user_form(id):
    """Edit existing user data"""
    user = User.query.get_or_404(id)
    form = EditUserForm(obj=user)
    # delete username and password from the edit form
    del form.username
    del form.password
    if form.validate_on_submit():
        user.email = form.email.data
        user.first_name = form.first_name.data
        user.last_name = form.last_name.data
        user.last_updated = datetime.datetime.utcnow()
        try:
            db.session.commit()
            flash("User account info saved", "success")
            if form.image.data:
                try:
                    img = Image.open(request.files[form.image.name])
                    width, height = img.size
                    img = img.crop((0, 0, min(width,
                                              height), min(width, height)))
                    upload_img(img, user)
                    user.has_img = True
                    user.last_updated = datetime.datetime.utcnow()
                    db.session.commit()
                except:
                    db.session.rollback()
                    flash("Image Error", 'error')
        except:
            db.session.rollback()
            flash("Changes could not be saved", 'error')
        return redirect(f'/users/{user.id}')
    return render_template('edit-user.html', user=user, form=form)
コード例 #24
0
def profile():
    """Update profile for current user."""

    # Check if a User is logged in
    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    user = User.query.get_or_404(g.user.id)
    form = EditUserForm(obj=user)

    if form.validate_on_submit():
        username = form.username.data
        email = form.email.data
        image_url = form.image_url.data
        header_image_url = form.header_image_url.data
        bio = form.bio.data
        password = form.password.data

        if User.authenticate(user.username, password):
            user.username = username
            user.email = email
            user.image_url = image_url
            user.header_image_url = header_image_url
            user.bio = bio

            db.session.commit()

            return redirect(f'/users/{user.id}')
        else:
            flash("Password Incorrect, you can't edit", "danger")
            return redirect('/')

    return render_template('users/edit.html', form=form)
コード例 #25
0
def edit_profile(username):
	""" Show Edit User Profile Form """

	if current_user.username != username:
		flash('Access unathorized', 'danger')
		return redirect(url_for('index'))

	user = current_user

	form = EditUserForm(obj=user)

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

		if user:
			try:
				user.username = form.username.data
				user.email = form.email.data
				db.session.commit()
				flash('User information updated', 'success')
				return redirect(url_for('index'))

			except:
				db.session.rollback()
				flash('Username taken.', 'danger')
		else:
			flash('Invalid credentials.', 'danger')
  
	return render_template('profile.html', 
		form=form, 
		btnText='Submit', 
		cancel='index', 
		color="#ACDAAA"
	)
コード例 #26
0
def update_profile():
    """Update profile for current user."""

    form = EditUserForm(obj=g.user)

    # user = User.query.get(session[CURR_USER_KEY])
    # IMPLEMENT THIS
    if form.validate_on_submit():
        if User.authenticate(g.user.username, form.password.data):
            # we don't need line 230 because we've done it g.user
            # user = User.query.get(session[CURR_USER_KEY])
            user = g.user
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data
            user.header_image_url = form.header_image_url.data
            user.bio = form.bio.data

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

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

    else:
        return render_template("users/edit.html", form=form)
コード例 #27
0
def edit_user():
    """Edit profile for user."""

    if not g.user:
        flash(NOT_LOGGED_IN_MSG, "danger")
        return redirect("/login")

    user = g.user

    # Do not display the static value of the default image
    # This will throw an error with the URL validator in wtforms
    if user.image_url == User._default_img:
        user.image_url = ''

    form = EditUserForm(obj=user)

    if form.validate_on_submit():
        form.populate_obj(user)

        # if the image_url is empty, then set the default again
        if not user.image_url:
            user.image_url = User._default_img

        db.session.commit()

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

    else:
        return render_template("profile/edit-form.html", form=form)
コード例 #28
0
def profile():
    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")
    user = User.query.get_or_404(g.user.id)
    form = EditUserForm()
    if form.validate_on_submit():
        if not User.authenticate(username=user.username,
                                 password=form.password.data):
            flash('Password incorrect!', category='danger')
            return redirect('/')
        user.username = form.username.data
        user.email = form.email.data
        if form.image_url.data:
            user.image_url = form.image_url.data
        if form.header_image_url.data:
            user.header_image_url = form.header_image_url.data
        user.bio = form.bio.data
        db.session.add(user)
        db.session.commit()
        return redirect(f'/users/{user.id}')

    else:
        form.username.data = user.username
        form.email.data = user.email
        form.image_url.data = user.image_url
        form.header_image_url.data = user.header_image_url
        form.bio.data = user.bio
    return render_template('/users/edit.html', form=form)
コード例 #29
0
def profile():
    """Update profile for current user."""

    ## if user not logged in, redirect
    if not g.user:
        return redirect('/')

    form = EditUserForm(obj=g.user)

    if form.validate_on_submit():
        pw = form.password.data
        user = User.authenticate(g.user.username, pw)  # returns user or false

        if user:

            for k, v in form.data.items():

                if k != 'csrf_token' and k != 'password':
                    setattr(user, k, v)
            db.session.commit()
            return redirect(f'/users/{g.user.id}')
        else:
            form.password.errors = ["invalid password"]

    return render_template('/users/edit.html', form=form)
コード例 #30
0
def edit_profile(user_id):
    """Displays form for user to edit user details (GET) and submits form (POST)"""

    if current_user.id == user_id:
        user = User.query.get_or_404(user_id)
        form = EditUserForm(obj=user)

        if form.validate_on_submit():
            user.username = form.username.data
            user.bio = form.bio.data
            user.location = form.location.data
            if form.img_url.data == "":
                db.session.commit()
                flash("Profile changes saved!", "success")
                return redirect(f"/user/{user.id}")
            else:
                user.profile_pic = form.img_url.data

            db.session.commit()

            flash("Profile changes saved!", "success")
            return redirect(f"/user/{user.id}")

        else:
            return render_template("edituser.html", form=form)
    else:
        return ("", 403)
コード例 #31
0
def profile():
    """Update profile for current user."""

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

    form = EditUserForm(obj=g.user)

    if form.validate_on_submit():

        # check if password is incorrect
        if not User.authenticate(g.user.username, form.password.data):
            form.password.errors = ['Password is incorrect. Try again.']
            return render_template('users/edit.html', form=form)

        g.user.username = form.username.data
        g.user.image_url = form.image_url.data or '/static/images/default-pic.png',
        g.user.header_image_url = form.header_image_url.data or '/static/images/warbler-hero.jpg',
        g.user.bio = form.bio.data

        db.session.commit()

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

    else:
        return render_template('users/edit.html', form=form)
コード例 #32
0
ファイル: app.py プロジェクト: richarddowdy/warbler
def profile():
    """Update profile for current user."""

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

    form = EditUserForm(obj=g.user)

    user = User.query.filter_by(id=g.user.id).first()

    if form.validate_on_submit():
        valid_user = User.authenticate(user.username, form.password.data)
        if valid_user:
            user.username = form.username.data
            user.email = form.email.data
            user.image_url = form.image_url.data
            user.header_image_url = form.header_image_url.data
            user.bio = form.bio.data
            user.location = form.location.data

            db.session.commit()

            return redirect(f'users/{g.user.id}')

        else:
            flash("Invalid credentials.", 'danger')
            return redirect(f'/users/{g.user.id}')
    else:
        return render_template('users/edit_profile.html', form=form)
コード例 #33
0
def profile():
    """Update profile for current user."""

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

    user = User.query.get(g.user.id)
    form = EditUserForm(obj=user)

    if form.validate_on_submit() and User.authenticate(form.username.data,
                                                       form.password.data):
        user.image_url = form.image_url.data
        user.header_image_url = form.header_image_url.data
        user.bio = form.bio.data
        user.location = form.location.data
        user.username = form.username.data
        user.email = form.email.data

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

        flash("Profile Updated Successfully", "success")
        return redirect(f"/users/{g.user.id}")
    else:
        flash("Password did not match. Please try again.", "danger")
        return render_template("/users/edit.html", form=form)

    return render_template("/users/edit.html", form=form)
コード例 #34
0
ファイル: app.py プロジェクト: DJTwoTone/Ask_Your_Rep
def edit_user():

    if not g.user:
        flash("Please sign up to access user functionality")
        return redirect("/signup")

    form = EditUserForm(obj=g.user)
    form.address.id = "search-input"
    form.address.type = "search"

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

        user = User.query.get_or_404(g.user.id)

        user.edit_user(first_name=first_name,
                       last_name=last_name,
                       email=email,
                       address=address)
        flash("Your persomal information has been successfully edited")
        return redirect("/user")

    return render_template("edit-user.html", form=form, user=g.user)
コード例 #35
0
ファイル: flaskmon.py プロジェクト: albertogg/Torrentbox
def user(username):
    """
    user <username> edit

    """
    if "username" in session:
        form = EditUserForm(request.form)
        user = User.query.filter_by(username=username).first()
        if user == None:
            return redirect(url_for("index"))
        else:
            if user.username == escape(session["username"]):
                if form.validate_on_submit():
                    user.username = form.username.data
                    user.email = form.email.data
                    user.password = generate_password_hash(form.password.data)
                    db.session.add(user)
                    db.session.commit()

                    session["username"] = user.username
                    # flash will display a message to the user
                    flash("Update Successful!")
                    # redirect user to the 'home' method of the user module.
                    return redirect(url_for("index"))
                else:
                    form.username.data = user.username
                    form.email.data = user.email
                return render_template("user.html", title="Edit User", user=user, form=form)
            else:
                return redirect(url_for("index"))
    else:
        return redirect(url_for("index"))
コード例 #36
0
ファイル: views.py プロジェクト: Anioko/flask-bones
def edit(id):
    user = User.query.filter_by(id=id).first_or_404()
    form = EditUserForm(obj=user)
    if form.validate_on_submit():
        form.populate_obj(user)
        user.update()
        flash('User %s edited' % user.username, 'success')
    return render_template('edit.html', form=form, user=user)
コード例 #37
0
ファイル: views.py プロジェクト: v-komarov/authbase
def	EditMyData(request):


    ### --- Получение кода учетной записи ---
    try:
	kod = GetUserKod(request)
    except:
	return HttpResponseRedirect('/')
	#return render_to_response("notaccess.html")

    error = ''


    if request.method == 'POST':
	form = EditUserForm(request.POST)
	error = form.errors
	if form.is_valid():
	    name1 = form.cleaned_data['name1']
	    name2 = form.cleaned_data['name2']
	    name3 = form.cleaned_data['name3']
	    job = form.cleaned_data['job']
	    phone_shot = form.cleaned_data['phone_shot']
	    phone_city = form.cleaned_data['phone_city']
	    phone_mob = form.cleaned_data['phone_mob']
	    phone_home = form.cleaned_data['phone_home']
	    email = form.cleaned_data['email']
	    dep = form.cleaned_data['dep']
	    status = form.cleaned_data['status']
	    login = form.cleaned_data['login']
	    passwd = form.cleaned_data['passwd']
	    #print form.cleaned_data
	    rec = GetRec(kod)
	    r = EditUser(kod,name1,name2,name3,job,phone_shot,phone_city,phone_mob,phone_home,email,rec[10],rec[12],login,passwd)


    form = EditUserForm(None)

    rec = GetRec(kod)
    form.fields['name1'].initial = rec[1]
    form.fields['name2'].initial = rec[2]
    form.fields['name3'].initial = rec[3]
    form.fields['job'].initial = rec[4]
    form.fields['phone_shot'].initial = rec[5]
    form.fields['phone_city'].initial = rec[6]
    form.fields['phone_mob'].initial = rec[7]
    form.fields['phone_home'].initial = rec[8]
    form.fields['email'].initial = rec[9]
    form.fields['dep'].initial = rec[10]
    form.fields['status'].initial = rec[12]
    form.fields['login'].initial = rec[13]
    form.fields['passwd'].initial = rec[14]

    form.fields['dep'].widget.attrs['disabled'] = True
    form.fields['status'].widget.attrs['disabled'] = True

    c = RequestContext(request,{'form':form,'error':error})
    c.update(csrf(request))
    return render_to_response("mydata/editmydata.html",c)
コード例 #38
0
ファイル: viewsSettings.py プロジェクト: HeinzHinek/AxiStore
def editUser(id=0):
    user = User.query.filter_by(id=id).first()
    form = EditUserForm(obj=user)
    customer_choices = [(a.id, a.name) for a in Customer.query.filter_by(customer_type=CUSTOMER_TYPES['TYPE_CUSTOMER']).all()]
    customer_choices = [(0, '')] + customer_choices
    maker_choices = [(a.id, a.name) for a in Maker.query.all()]
    maker_choices = [(0, '')] + maker_choices
    form.customer.choices = customer_choices
    form.maker.choices = maker_choices

    if form.validate_on_submit():
        if len(User.query.filter_by(nickname=form.nickname.data).all()) > 1:
            flash(gettext("Selected username already exists!"))
            return redirect(url_for('users'))

        new_email = form.email.data
        check_mail = User.query.filter_by(email=new_email).all()

        #user mail already exists
        if len(check_mail) > 0 and new_email != user.email:
            flash(gettext('Selected email is already in use!'))
            return redirect(url_for('users'))

        user.nickname = form.nickname.data
        user.email = form.email.data
        user.role = form.role.data

        if int(form.role.data) == USER_ROLES['ROLE_CUSTOMER']:
            if form.customer.data and form.customer.data != '' and form.customer.data != 0:
                user.customer_id = form.customer.data
                user.maker_id = None
            else:
                user.customer_id = None
        elif int(form.role.data) == USER_ROLES['ROLE_MAKER']:
            if form.maker.data and form.maker.data != '' and form.maker.data != 0:
                user.maker_id = form.maker.data
                user.customer_id = None
            else:
                user.maker_id = None
        else:
            user.customer_id = None
            user.maker_id = None

        user.language = form.language.data
        db.session.add(user)
        db.session.commit()
        flash(gettext("User details succesfully changed."))
        return redirect(url_for("users"))
    selected_customer = user.customer_id if user.customer_id else 0
    selected_maker = user.maker_id if user.maker_id else 0
    return render_template('settings/editUser.html',
                           title=gettext("Edit User"),
                           USER_ROLES=USER_ROLES,
                           selected_customer=selected_customer,
                           selected_maker=selected_maker,
                           form=form)
コード例 #39
0
ファイル: fahrtenbuch.py プロジェクト: brnc69/pythonshit
def user_edit(user_id):
    user = User.query.filter_by(id=user_id).first()
    form = EditUserForm(obj=user)
    if form.validate_on_submit():
        form.populate_obj(user)
        db_session.add(user)
        db_session.commit()
        flash('Nutzerdaten erfolgreich aktualisiert!')
        return redirect(url_for('user_list'))
    return render_template('user_edit.jinja', form=form, user=user)
コード例 #40
0
ファイル: views.py プロジェクト: dustinfarris/todo
def _update(request, pk):
  user = get_object_or_404(User, pk=pk)
  if user != request.user and not request.user.is_superuser:
    return HttpResponseForbidden()
  form = EditUserForm(request.POST)
  if form.is_valid():
    updated_user = form.save()
    messages.success(request, "User edit successful.")
    return redirect(updated_user)
  return edit(request, pk, form)
コード例 #41
0
ファイル: views.py プロジェクト: eduardogpg/admin_facilito
def edit_client(request):
	form_client = EditClientForm(request.POST or None, instance = client_instance(request.user) )
	form_user = EditUserForm(request.POST or None, instance= request.user)

	if request.method == 'POST':
		if form_client.is_valid() and form_user.is_valid():
			form_user.save()
			form_client.save()	
			messages.success(request, 'Datos actualizados correctamente')
	return render(request, 'client/edit.html', {'form_client' : form_client, 'form_user': form_user})
コード例 #42
0
ファイル: views.py プロジェクト: succor-app/study_buddy
def edit_user():
    form = EditUserForm()
    user = current_user  
    if form.validate_on_submit():
        user.name.first = re.sub('<[^>]*>', '', request.form['first_name'])
        user.name.last = re.sub('<[^>]*>', '', request.form['last_name'])
        user.name.full = titleize(user.name.first + ' ' + user.name.last)
        user.save()
        return redirect(url_for('user', user_id=user._id))
    return render_template('edit_user.html', user=user)
コード例 #43
0
ファイル: user.py プロジェクト: ccc520/adminset
def user_edit(request, ids):
    user = get_user_model().objects.get(id=ids)
    if request.method == 'POST':
        form = EditUserForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            status = 1
        else:
            status = 2
    else:
        form = EditUserForm(instance=user)
    return render(request, 'accounts/user_edit.html', locals())
コード例 #44
0
def profile_edit():
    eForm = EditUserForm(g.user.nickname)
    if eForm.validate_on_submit():
        g.user.nickname = eForm.nickname.data
        g.user.about_me = eForm.about_me.data
        db.session.add(g.user)
        db.session.commit()
        flash('Your profile has been saved.', 'success')
    else:
        eForm.nickname.data = g.user.nickname
        eForm.about_me.data = g.user.about_me
    return redirect(request.args.get('next') or url_for('user', nickname=g.user.nickname))
コード例 #45
0
ファイル: users.py プロジェクト: dreamcity/Spark_Movie_recsys
def update_user_info():
	user_id = int(request.args.get('user_id',0))
	if user_id :
		form = EditUserForm()
		if form.validate_on_submit():
			user_info = {}
			user_info["name"] = form.name.data
			user_info["age"] = form.age.data
			user_info["gender"] = form.gender.data
			user_info["occupation"] = form.occupation.data
			current_app.config['USERS_COLLECTION'].update_one({"id":user_id},{'$set':user_info},upsert = True)
			return redirect(url_for('.show_user_f_id',user_id = user_id))
		return render_template('edit_user_form.html',form=form)		
 	return redirect(url_for('.show_user_f_id',user_id = user_id))
コード例 #46
0
ファイル: views.py プロジェクト: Bartzi/django-multimail
 def post(self, request):
     if request.POST['form-name'] == 'edit-user-form':
         add_email_form = AddEmailForm()
         edit_user_form = EditUserForm(request.POST, instance=request.user)
         if edit_user_form.is_valid():
             edit_user_form.save()
             return redirect('/profile/')
     if request.POST['form-name'] == 'add-email-form':
         edit_user_form = EditUserForm(instance=request.user)
         add_email_form = AddEmailForm(request.POST)
         if add_email_form.is_valid():
             add_email_form.save()
             return redirect('/profile/')
     page_title = 'Profile'
     return render_to_response('profile.html', locals(),
         context_instance=RequestContext(request))
コード例 #47
0
ファイル: views.py プロジェクト: kmooney/julython.org
def edit_profile(request, username, template_name='people/edit.html'):
    from forms import EditUserForm
    user = User.get_by_auth_id('own:%s' % username)

    if user == None:
        raise Http404("User not found")
    
    if user.key != request.user.key:
        http403 = HttpResponse("This ain't you!")
        http403.status = 403
        return http403
    
    existing_slug = str(user.location_slug)
    existing_team = str(getattr(user, 'team_slug', ''))
    form = EditUserForm(request.POST or None, user=request.user)
    if form.is_valid():
        for key, value in form.cleaned_data.iteritems():
            if key == 'email':
                # Don't save the email to the profile
                continue
            if key == 'team':
                # slugify the team to allow easy lookups
                setattr(user, 'team_slug', slugify(value))
            setattr(user, key, value)
        user.put()
        
        if user.location_slug != existing_slug:
            # Defer a couple tasks to update the locations
            deferred.defer(fix_location, str(user.location_slug))
            deferred.defer(fix_location, existing_slug)
            
        if getattr(user, 'team_slug', '') != existing_team:
            # Defer a couple tasks to update the teams
            deferred.defer(fix_team, str(user.team_slug))
            deferred.defer(fix_team, existing_team)
            
        return HttpResponseRedirect(
            reverse('member-profile',
                    kwargs={'username':request.user.username}
                   )
        )

    return render_to_response(template_name,
        {'form':form},
        context_instance=RequestContext(request))
コード例 #48
0
ファイル: views.py プロジェクト: ericho99/dportims
def editprofile():
    if cas.username is None:
        return redirect('/login')
    user = Player.query.filter(Player.netid==cas.username).first()
    if user is None:
        return redirect('/newuser')

    form = EditUserForm()
    if form.validate_on_submit():
        if not name_check(form.name.data,1):
            return render_template('editprofile.html',user=user,form=form,validname=0)
        user.name = form.name.data
        user.email = form.email.data
        db.session.commit()
        return redirect('/index')
    form.name.data = user.name
    form.email.data = user.email
    return render_template('editprofile.html',user=user,form=form,validname=1)
コード例 #49
0
ファイル: views.py プロジェクト: baa-archieve/esyakutuphanesi
def edit_profile():
    form = EditUserForm()

    if request.method == 'POST' and form.validate_on_submit():
        if current_user.id == int(form.userid.data):
            photo_file = form.photo.data

            if photo_file:
                file_ext = get_file_extension(photo_file.filename)
                generated_name = str(uuid.uuid1()) + '.' + file_ext

                current_user_id = str(current_user.id)
                folder_path = app.config['UPLOADS_FOLDER'] + '/user/' + current_user_id + '/'
                new_folder = os.path.dirname(folder_path)
                if not os.path.exists(new_folder):
                    os.makedirs(new_folder)

                filepath = os.path.join(folder_path, generated_name)

                photo_file.save(filepath)

                new_photo = Photo(owner=current_user, filename='user/' + current_user_id + '/' + generated_name)
                db.session.add(new_photo)
                db.session.commit()

                User.query.filter(User.id == current_user.id).\
                    update({User.photo: new_photo.filename})

            User.query.filter(User.id == current_user.id).\
                update({User.name: form.name.data,
                        User.email: form.email.data,
                        User.phone_number: form.phone_number.data,
                        User.about: form.about.data})
            db.session.commit()

            flash(u"Profil güncellendi.", current_user.id)

    form.fill_form(current_user)

    return render_template(
        'edit_profile.html',
        form=form,
        user=current_user
    )
コード例 #50
0
ファイル: views.py プロジェクト: bireme/scielobooks
def edit_user(request):
    FORM_TITLE = _('Edit User')
    main = get_renderer(BASE_TEMPLATE).implementation()
    localizer = get_localizer(request)
    publishers = request.rel_db_session.query(models.Publisher.name_slug, models.Publisher.name).all()
    edit_user_form = EditUserForm.get_form(localizer,publishers)

    if request.method == 'POST':
        if 'btn_cancel' in request.POST:
            return HTTPFound(location=request.route_path('users.list'))

        controls = request.POST.items()
        try:
            appstruct = edit_user_form.validate(controls)
        except deform.ValidationFailure, e:

            return {'content':e.render(),
                    'main':main,
                    'general_stuff':{'form_title':FORM_TITLE,
                                  'breadcrumb': [
                                    (_('Dashboard'), request.route_path('staff.panel')),
                                    (_('Manage Users'), request.route_path('users.list')),
                                    (FORM_TITLE, None),
                                  ]
                                 },
                    'user':get_logged_user(request),
                    }

        try:
            user = request.rel_db_session.query(users.User).filter_by(id=appstruct['_id']).one()
        except NoResultFound:
            raise exceptions.NotFound()

        if appstruct['password'] is not None:
            user.password = SHA256.new(appstruct['password']).hexdigest()
            user.password_encryption = 'SHA256'

        if len(appstruct['email']):
            user.email = appstruct['email']

        if appstruct['group'] != user.group.name:
            group = request.rel_db_session.query(users.Group).filter_by(name=appstruct['group']).one()
            user.group = group

        request.rel_db_session.add(user)
        try:
            request.rel_db_session.commit()
        except:
            request.rel_db_session.rollback()
            request.session.flash(_('Problems occured when trying to update user data. Please try again.'))
        else:
            request.session.flash(_('Successfully updated.'))

        return HTTPFound(location=request.route_path('users.edit_user', id=user.id))
コード例 #51
0
ファイル: views.py プロジェクト: benfrisbie/pantry
def edit_user():
    form = EditUserForm()
    
    if form.validate_on_submit():
        g.user.first_name = form.first_name.data
        g.user.last_name = form.last_name.data
        #if form.image is not None or form.image != "":
        if form.image:
            form.image.data.save(os.path.join(PROFILE_IMAGE_PATH, '%d.jpg' % g.user.id))
            g.user.image = "/uploads/profile_images/%d.jpg"% g.user.id
        db.session.merge(g.user)
        db.session.commit()
        flash('Your profile has been updated')
        return redirect(url_for('index'))

    else:
        form.first_name.data = g.user.first_name
        form.last_name.data = g.user.last_name
    
    return render_template('edit_user.html', title = 'Edit Profile', form = form, user = g.user, action = 'Update')
コード例 #52
0
ファイル: views.py プロジェクト: bartlett705/microblog
def edit_user():
    form = EditUserForm(g.user.handle)
    if form.validate_on_submit():
        g.user.handle = form.handle.data
        g.user.about_me = form.about_me.data
        g.user.email = form.email.data
        g.user.pic_url = form.pic_url.data
        db.session.add(g.user)
        db.session.commit()
        flash(choice(app.config['MSG']['confirm_post']))
        app.logger.info(g.user.handle, ' changed something.')
        return redirect(url_for('user', handle=g.user.handle, page=1))
    else:
        form.handle.data = g.user.handle
        form.about_me.data = g.user.about_me
        form.email.data = g.user.email
        form.pic_url.data = g.user.pic_url
        if form.handle.errors:
            flash(form.handle.errors[0])
    return render_template('edit_user.html', form=form, user=g.user)
コード例 #53
0
def edit_user(request, org_url, user_id):
    organization = request.organization
    user = settings.AUTH_USER_MODEL.objects.get(id=user_id)
    form = EditUserForm(request.POST or None, instance=user)

    if form.is_valid():
        form.save()
        return redirect(
            "set_organization_group", [org_url, "staff_group"]
        )

    return render(
        request,
        "organizations/user_new.html",
        dict(
            form=form,
            org=organization,
            org_url=org_url,
        )
    )
コード例 #54
0
ファイル: views.py プロジェクト: sennevanbaelen/EKbetass
def editProfile():
    error = None
    form = EditUserForm(request.form)
    username_before = request.args.get("usr")
    user = User.query.filter_by(userName=username_before).first()
    if request.method == "POST":
        if form.validate_on_submit():
            if bcrypt.check_password_hash(user.password, request.form["password"]):
                firstname = request.form["firstname"]
                lastname = request.form["lastname"]
                username = request.form["username"]
                email = request.form["email"]
                session["userName"] = username
                session["firstName"] = firstname
                session["lastName"] = lastname
                session["email"] = email

                # Update
                db.session.query(User).filter_by(userName=username_before).update({User.firstName: firstname})
                db.session.query(User).filter_by(userName=username_before).update({User.lastName: lastname})
                db.session.query(User).filter_by(userName=username_before).update({User.userName: username})
                db.session.query(Scores).filter_by(userName=username_before).update({Scores.userName: username})
                db.session.query(User).filter_by(userName=username_before).update({User.email: email})

                if request.form["newPassword"] != "":
                    newPassword = bcrypt.generate_password_hash(form.newPassword.data)
                    db.session.query(User).filter_by(userName=username_before).update({User.password: newPassword})

                db.session.commit()
                return redirect(url_for("appHome.profile"))

            else:
                error = "Invalid password"
                return render_template("editProfile.html", form=form, error=error, user=user)

        else:
            return render_template("editProfile.html", form=form, error=error, user=user)

    if request.method == "GET":
        return render_template("editProfile.html", form=form, user=user)
コード例 #55
0
ファイル: views.py プロジェクト: v-komarov/authbase
def	New(request):

    error = ''


    if CheckAccess(request,'20') != 'OK':
	return render_to_response("notaccess.html")

    if request.method == 'POST':
	form = EditUserForm(request.POST)
	error = form.errors
	if form.is_valid():
	    name1 = form.cleaned_data['name1']
	    name2 = form.cleaned_data['name2']
	    name3 = form.cleaned_data['name3']
	    job = form.cleaned_data['job']
	    phone_shot = form.cleaned_data['phone_shot']
	    phone_city = form.cleaned_data['phone_city']
	    phone_mob = form.cleaned_data['phone_mob']
	    phone_home = form.cleaned_data['phone_home']
	    email = form.cleaned_data['email']
	    dep = form.cleaned_data['dep']
	    status = form.cleaned_data['status']
	    login = form.cleaned_data['login']
	    passwd = form.cleaned_data['passwd']
	    #print form.cleaned_data
	    r = AddUser(name1,name2,name3,job,phone_shot,phone_city,phone_mob,phone_home,email,dep,status,login,passwd)
	    if r == 'OK':
		return HttpResponseRedirect('/users')
    else:
	form = EditUserForm()
#	form.fields['passwd'].initial = commands.getoutput('authbase/lib/genpass')
	form.fields['passwd'].initial = CreatePassword()


    
    c = RequestContext(request,{'form':form,'error':error})
    c.update(csrf(request))
    return render_to_response("users/new.html",c)
コード例 #56
0
ファイル: views.py プロジェクト: pombredanne/Workgroup
def edit_profile(request, username):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/welcome/')

    usr = get_object_or_404(User, username=username)
    if usr.id != request.user.id and not request.user.is_superuser():
        messages.error(request, _("Недостаточно прав!"))
        return HttpResponseRedirect(request.META.get('HTTP_REFERER') or '/')
    else:
        if request.method == "POST":
            edit_form = EditUserForm(request.POST)
            if edit_form.is_valid():
                first_name = edit_form.cleaned_data.get('first_name')
                last_name = edit_form.cleaned_data.get('last_name')
                email = edit_form.cleaned_data.get('email')
                if first_name != usr.first_name or last_name != usr.last_name or email != usr.email:
                    usr.first_name = first_name
                    usr.last_name = last_name
                    usr.email = email
                    usr.save()
                messages.success(request, _("Информация успешно изменена."))

    return HttpResponseRedirect('/user/' + usr.username + '/')
コード例 #57
0
ファイル: views.py プロジェクト: romanlevin/julython.org
def edit_profile(request, username, template_name='people/edit.html'):
    from forms import EditUserForm
    user = request.user

    if user == None:
        raise Http404("User not found")
    
    if user.username != request.user.username:
        http403 = HttpResponse("This ain't you!")
        http403.status = 403
        return http403
    
    form = EditUserForm(request.POST or None, user=request.user)

    if form.is_valid():
        for key, value in form.cleaned_data.iteritems():
            if key in ['email', 'gittip']:
                # Don't save the email to the profile
                continue
            if key == 'team':
                # slugify the team to allow easy lookups
                setattr(user, 'team_slug', slugify(value))
            setattr(user, key, value)
        user.save()

        return HttpResponseRedirect(
            reverse('member-profile',
                    kwargs={'username':request.user.username}
                   )
        )

    return render_to_response(template_name, {
            'form': form, 
            'profile': user,
            'active': 'edit',
        }, 
        context_instance=RequestContext(request))
コード例 #58
0
ファイル: views.py プロジェクト: JrtPec/coopkot
def edit_user(id):
    user = User.query.get(id)
    if user == None:
        flash("User not found")
        abort(404)

    form = EditUserForm()
    form.property.choices = [(p.id, p.name) for p in Property.query.order_by('name')]
    form.property.choices.insert(0,(0,None))
    form.role.choices = [(ROLE_USER,"user"),(ROLE_LANDLORD,"landlord"),(ROLE_ADMIN,"admin")]

    if form.validate_on_submit():
        if form.property.data != 0:
            user.property_id = form.property.data
        else:
            user.property_id = None
        user.role = form.role.data
        db.session.add(user)
        db.session.commit()
        flash('Your changes have been saved.')
        return redirect(url_for('users'))
    return render_template('edit_user.html',
        user = user,
        form = form)
コード例 #59
0
ファイル: views.py プロジェクト: sennevanbaelen/EKbetass
def editUser(): 
    error = None      
    form = EditUserForm(request.form)
    username_before=request.args.get('usr')
    user=User.query.filter_by(userName=username_before).first()
    if request.method == 'POST':
        if form.validate_on_submit():
            firstname=request.form['firstname']
            lastname=request.form['lastname']
            username=request.form['username']
            email=request.form['email']
            validated=request.form['validated']
            activated=request.form['activated']
            activation_before=user.activated
           
            #Update           
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.firstName: firstname})
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.lastName: lastname})
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.userName: username})
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.email: email})
            import ast
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.validated: ast.literal_eval(validated)})
            db.session.query(User).filter_by(userName=username_before)\
                .update({User.activated: ast.literal_eval(activated)})
            db.session.commit() 
                       
            if activation_before == False and activated == 'True':
                print "here"
                import smtplib
                from email.mime.multipart import MIMEMultipart
                from email.mime.text import MIMEText
                from email.MIMEImage import MIMEImage
                
                
                # Writing the message (this message will appear in the email)
                fromAddress='*****@*****.**'
                toAddress= user.email
                
                msg = MIMEMultipart()                
                msg['Subject'] = "Your bets EURO2016 account is activated"
                msg['From'] = fromAddress
                msg['To'] = user.email
                
                body =  """Hi {0},
                
Thanks again for being part of this kick ass EURO 2016 betting app! \n
Your bank transfer is completed and your account is therefore activated. 
             
http://bets-euro2016.herokuapp.com/home/ 
Go Crazy! 
              
Kind regards,

Senne & Louis 
                                          
""".format(user.userName)
                msg.attach(MIMEText(body, 'plain'))
                
                text = msg.as_string()
                                   
                # Gmail Login    
                usrname = '*****@*****.**'
                password = '******'
                
                # Sending the mail
                
                server = smtplib.SMTP('smtp.gmail.com:587')
                server.starttls()
                server.login(usrname,password)
                server.sendmail(fromAddress, toAddress, text)
                server.quit()
                #here comes the automatic mail code 
            return redirect(url_for('admin.checkDatabase'))        

        else:
            user.validated=str(user.validated)
            user.activated=str(user.activated)
            return render_template("editUser.html",form=form,error=error,user=user)
            
    if request.method == 'GET':
        user.validated=str(user.validated)
        user.activated=str(user.activated)
        return render_template('editUser.html', form=form,user=user)
コード例 #60
0
ファイル: views.py プロジェクト: LDAR2011/LDashboard
def UserMain(request):
    rolename = utils.get_rolename_by_username(request.user)
    return_dict = {'rolename':rolename, 'username':request.user, 'windowname':'None'}
    
    #add user
    adduserform = AddUserForm()
    return_dict['addUserForm'] = adduserform
    
    edituserform = EditUserForm()
    return_dict['editUserForm'] = edituserform
    
    if request.method == "POST":
        if request.POST.get('formtype') == 'add':
            adduserform = AddUserForm(request.POST)
            if adduserform.is_valid():
                
                if User.objects.filter(username=adduserform.fields.get('username')).count() == 0:
                    
                    user = User.objects.create_user(adduserform.fields.get('username'), adduserform.fields.get('email'),\
                            adduserform.fields.get('password'))
                    user.save()
                    userrole_list = UserRole.objects.filter(username=adduserform.fields.get('username'))
                    if userrole_list.count() != 0:
                        userrole_list.delete()
                    
                    userrole = UserRole(username=user.username, rolename=adduserform.fields.get('rolename'),\
                                domain=adduserform.fields.get('domain'),realname=adduserform.fields.get('realname'))                    
                    userrole.save()
                    
                    return_dict['windowname'] = 'successwindow'
                    return_dict['windowmessage'] = u'增加用户成功'
                    
                else:
                    return_dict['windowname'] = 'errorwindow'
                    return_dict['windowmessage'] = u'用户名已存在,请更换用户名'
                    
            else:
                return_dict['windowname'] = 'errorwindow'
                return_dict['windowmessage'] = adduserform.error_message
                
        if request.POST.get('formtype') == 'edit':
            edituserform = EditUserForm(request.POST)
            if edituserform.is_valid():
                
                user = User.objects.get(username=edituserform.fields.get('username'))
                userrole = UserRole.objects.get(username=edituserform.fields.get('username'))
                
                user.email = edituserform.fields.get('email')
                userrole.rolename, userrole.domain, userrole.realname = \
                    edituserform.fields.get('rolename'),edituserform.fields.get('domain'),edituserform.fields.get('realname')
                
                user.save()
                userrole.save()
                
                return_dict['windowname'] = 'successwindow'
                return_dict['windowmessage'] = u'修改用户属性成功'
                
            else:
                return_dict['windowname'] = 'errorwindow'
                return_dict['windowmessage'] = edituserform.error_message
                
        if request.POST.get('formtype') == 'delete':
            
            deleteusername = request.POST.get('username','')
            print 'deleteusername:'******'windowname'] = 'errorwindow'
                return_dict['windowmessage'] = u'不能删除自己'
            
            User.objects.filter(username=deleteusername).delete()
            UserRole.objects.filter(username=deleteusername).delete()
            
            return_dict['windowname'] = 'successwindow'
            return_dict['windowmessage'] = u'删除用户成功'

    #list user
    users = User.objects.all()
    userinfos = []
    for user in users:
        userinfos.append(UserInfo(user))
    
    
    paginator = Paginator(userinfos, 25)
    
    try:
        page = request.GET.get('page','1')
        userinfos = paginator.page(page)
    except PageNotAnInteger:
        userinfos = paginator.page(1)
    except EmptyPage:
        userinfos = paginator.page(paginator.num_pages)
    except Exception:
        userinfos = paginator.page(1)
        
    
    return_dict['userlist'] = userinfos
    print userinfos.number
    
    return render_to_response('UserManage/user.html',return_dict, RequestContext(request))