from flask import flash, redirect, render_template, url_for from flask_login import login_required from . import admin from .forms import EditUserForm from .. import db from ..decorators import admin_required from ..models import Role, User from ..profile import tasks as profile_tasks @admin.route('/users') @login_required @admin_required def users(): users = User.query.all() users = [dict(username=u.username, email=u.email, role_id=u.role_id, confirmed=u.confirmed, id=u.id) for u in users] return render_template('admin/users.html.j2', title='Users', users=users) @admin.route('/users/') @login_required @admin_required def user(user_id): user = User.query.get_or_404(user_id) return render_template('admin/user.html.j2', title='Edit user', user=user) @admin.route('/users//delete') @login_required @admin_required def delete_user(user_id): profile_tasks.delete_user(user_id) flash('User has been deleted!') return redirect(url_for('admin.index')) @admin.route('/users//edit', methods=['GET', 'POST']) @login_required @admin_required def edit_user(user_id): user = User.query.get_or_404(user_id) edit_user_form = EditUserForm(user=user) if edit_user_form.validate_on_submit(): user.email = edit_user_form.email.data user.username = edit_user_form.username.data user.confirmed = edit_user_form.confirmed.data user.role = Role.query.get(edit_user_form.role.data) db.session.add(user) db.session.commit() flash('The profile has been updated.') return redirect(url_for('admin.edit_user', user_id=user.id)) edit_user_form.email.data = user.email edit_user_form.username.data = user.username edit_user_form.confirmed.data = user.confirmed edit_user_form.role.data = user.role_id return render_template('admin/edit_user.html.j2', edit_user_form=edit_user_form, title='Edit user', user=user)