我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用flask_login.current_user.name()。
def list_user(): users = User.query.order_by(User.name).all() users = sorted(users, key=lambda u: u.name) if not current_user.role.is_administrator: masked = [] for user in users: guest = Guest() guest.name = user.name guest.email = user.email guest.role = user.role if not user.role.is_administrator else UserRole.security_team guest.active = user.active if user.active: masked.append(guest) users = masked users = sorted(users, key=lambda u: u.role) return render_template('admin/user.html', title='User list', users=users)
def create_user(): form = UserForm() if not form.validate_on_submit(): return render_template('admin/form/user.html', title='Create user', form=form, User=User, password_length={'min': TRACKER_PASSWORD_LENGTH_MIN, 'max': TRACKER_PASSWORD_LENGTH_MAX}) password = random_string() if not form.password.data else form.password.data salt = random_string() user = db.create(User, name=form.username.data, email=form.email.data, salt=salt, password=hash_password(password, salt), role=UserRole.fromstring(form.role.data), active=form.active.data) db.session.commit() flash('Created user {} with password {}'.format(user.name, password)) return redirect('/user')
def validate(self): rv = BaseForm.validate(self) if not rv: return False if current_user.name in self.password.data: self.password.errors.append(ERROR_PASSWORD_CONTAINS_USERNAME) return False if self.password.data != self.password_repeat.data: self.password_repeat.errors.append(ERROR_PASSWORD_REPEAT_MISMATCHES) return False if not compare_digest(current_user.password, hash_password(self.password_current.data, current_user.salt)): self.password_current.errors.append(ERROR_PASSWORD_INCORRECT) return False return True
def test_edit_user(db, client): new_password = random_string() new_email = '{}foo'.format(EMAIL) new_role = UserRole.security_team resp = client.post(url_for('edit_user', username=USERNAME), follow_redirects=True, data=dict(username=USERNAME, email=new_email, password=new_password, role=new_role.name, active=True)) assert resp.status_code == 200 resp = client.post(url_for('logout'), follow_redirects=True) assert_not_logged_in(resp) resp = client.post(url_for('login'), follow_redirects=True, data={'username': USERNAME, 'password': new_password}) assert_logged_in(resp) assert USERNAME == current_user.name assert new_email == current_user.email assert new_role == current_user.role
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user)
def search_biblio(): """Search entries in biblio.""" # Get the form corresponding to the query: form = ExtendedSearchForm() if form.validate_on_submit(): if form.source.data == "local": s = "%" + form.name.data + "%" # Send request to database: bibdat = convert_rows_to_dict(db.session.query(BiblioEntry)\ .filter(or_(BiblioEntry.authors.like(s), BiblioEntry.title.like(s)))) # Format bibdat and sort by years: templateVars = format_bibdatabase(bibdat) if len(bibdat) == 0: flash("No entry found") return render_template("references.html", **templateVars) elif form.source.data == "hal": redirect("/hal/"+form.name.data) else: flash("Not implemented yet") return redirect("/biblio")
def add_entry(): """Add a new entry to the bibliography.""" form = BiblioForm() if form.validate_on_submit(): bib_entry = BiblioEntry(ID=form.ID.data, ENTRYTYPE=form.typ.data, authors=form.author.data, title=form.title.data, year=form.year.data, school="", publisher="", keywords=form.keywords.data, url=form.url.data, journal=form.journal.data) db.session.add(bib_entry) user = current_user.name event = Event(author=user, article=form.ID.data, event="ADD", time=time.time()) db.session.add(event) db.session.commit() return redirect("/biblio") return redirect("/biblio")
def post_comment(): """Add post to article.""" form = PostForm() article = request.environ["HTTP_REFERER"].split("=")[-1] tim = time.time() user = current_user.name post = Post(author=user, article=article, message=form.message.data, time=tim) db.session.add(post) user = current_user.name event = Event(author=user, article=article, event="COMMENT", time=time.time()) db.session.add(event) db.session.commit() return redirect("/biblio/article=" + article)
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) db.session.commit() flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user)
def request_orcid_credentials(): """Redirect to the ORCID for the technical conact of the organisation. Additionally the time stamp gets saved when the handler gets invoked. """ client_secret_url = append_qs( iri_to_uri(MEMBER_API_FORM_BASE_URL), new_existing=('Existing_Update' if current_user.organisation.confirmed else 'New_Credentials'), note=NOTE_ORCID + " " + current_user.organisation.name, contact_email=current_user.email, contact_name=current_user.name, org_name=current_user.organisation.name, cred_type=CRED_TYPE_PREMIUM, app_name=APP_NAME + " for " + current_user.organisation.name, app_description=APP_DESCRIPTION + current_user.organisation.name + "and its researchers", app_url=APP_URL, redirect_uri_1=url_for("orcid_callback", _external=True)) current_user.organisation.api_credentials_requested_at = datetime.now() current_user.organisation.save() return redirect(client_secret_url)
def __init__(self, model=None, *args, **kwargs): """Pick the model based on the ModelView class name assuming it is ModelClass + "Admin".""" if model is None: if hasattr(self, "model"): model = self.model else: model_class_name = self.__class__.__name__.replace("Admin", '') model = globals().get(model_class_name) if model is None: if model_class_name not in dir(models): raise Exception(f"Model class {model_class_name} doesn't exit.") model = models.__dict__.get(model_class_name) super().__init__(model, *args, **kwargs) # TODO: remove whent it gets merged into the upsteem repo (it's a workaround to make # joins LEFT OUTERE)
def get_export_name(self, export_type='csv'): """Get export file name using the original imported file name. :return: The exported csv file name. """ task_id = request.args.get("task_id") if task_id: try: task = Task.get(id=task_id) filename = os.path.splitext(task.filename)[0] return "%s_%s.%s" % (filename, datetime.now().strftime("%Y-%m-%d_%H-%M-%S"), export_type) except Task.DoesNotExist: flash(f"The batch task doesn't exist", "danger") abort(404) return super().get_export_name(export_type=export_type)
def edit_profile_admin(id): user= User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role=Role.query.get(form.role.data) user.name = form.name.data user.location=form.location.data user.about_me=form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user)
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email=form.email.data user.username=form.username.data user.role = Role.query.get(form.role.data) user.name=form.name.data user.location=form.location.data user.about_me=form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username=username)) form.email.data=user.email form.username.data=user.username form.role.data=user.role_id form.name.data=user.name form.location.data=user.location form.about_me.data=user.about_me return render_template('edit-profile.html', form=form, user=user)
def profile_settings(username): user = User.query.filter_by(name=username).first_or_404() form = ProfileSettings() if form.validate_on_submit(): # POST request user.bio = form.bio.data user.website = form.website.data db.session.add(user) db.session.commit() flash("new settings were successfully applied", "success") view = "posts.user_profile_posts" return redirect(url_for(view, username=user.name)) # GET request if current_user.is_authenticated and current_user.name == user.name: form.website.data = current_user.website form.bio.data = current_user.bio return render_template("profile_settings.html", form=form, user_bio=user.bio, title="profile settings" ) else: return abort(403)
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confimed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confimed.data = user.confimed form.role.data = user.role_id form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user)
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.filter_by(id = form.role.data).first() user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user)
def login(): """ login a user :return: response """ content = request.get_data(True, as_text=True) login_data = json.loads(content) if ('name' in login_data) and ('password' in login_data): name = login_data['name'] password = login_data['password'] remember = login_data['remember'] if 'remember' in login_data else False credential = UserCredential.login_user(name, password) login_user(credential, remember=remember) return json_resp({'msg': 'OK'}) else: raise ClientError(ClientError.INVALID_REQUEST)
def register(): """ register a new user using invite code, note that a newly registered user is not administrator, you need to use an admin user to promote it :return: response """ content = request.get_data(True, as_text=True) register_data = json.loads(content) if ('name' in register_data) and ('password' in register_data) and ('password_repeat' in register_data) and ('invite_code' in register_data) and ('email' in register_data): name = register_data['name'] password = register_data['password'] password_repeat = register_data['password_repeat'] email = register_data['email'] invite_code = register_data['invite_code'] if password != password_repeat: raise ClientError(ClientError.PASSWORD_MISMATCH) if UserCredential.register_user(name=name, password=password, email=email, invite_code=invite_code): # login automatically credential = UserCredential.login_user(name, password) login_user(credential, remember=False) # send email credential.send_confirm_email() return json_resp({'message': 'ok'}, 201) else: raise ClientError(ClientError.INVALID_REQUEST)
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if form.validate_on_submit(): user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash(u'?????') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user)
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.about_me = form.about_me.data db.session.add(current_user) flash('Your profile has benn updated') return redirect(url_for('.user',username=current_user.username)) form.name.data = current_user.name form.location.data = current_user.location form.about_me.data = current_user.about_me return render_template('edit_profile.html',form=form) #?????????????
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm() if form.validate_on_submit(): user.email= form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.role = Role.query.get(form.role.data) user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash('The profile has been updated.') return redirect(url_for('.user', username=user.username)) form.email.data = user.email form.username.data = user.username form.confirmed.data = user.confirmed form.role.data = user.role_id form.name.data = user.name form.location.data = user.location form.about_me.data = user.about_me return render_template('edit_profile.html', form=form, user=user) #?????????
def delete_user(username): user = User.query.filter_by(name=username).first() if not user: return not_found() form = ConfirmForm() title = 'Delete {}'.format(username) if not form.validate_on_submit(): return render_template('admin/form/delete_user.html', title=title, heading=title, form=form, user=user) if not form.confirm.data: return redirect('/user') active_admins = User.query.filter_by(active=True, role=UserRole.administrator).count() if user.id == current_user.id and 1 >= active_admins: return forbidden() user_invalidate(user) db.session.delete(user) db.session.commit() flash('Deleted user {}'.format(user.name)) return redirect('/user')
def test_edit_preserves_password(db, client): new_email = '{}foo'.format(EMAIL) resp = client.post(url_for('edit_user', username=USERNAME), follow_redirects=True, data=dict(username=USERNAME, email=new_email, active=True)) assert resp.status_code == 200 resp = client.post(url_for('logout'), follow_redirects=True) assert_not_logged_in(resp) resp = client.post(url_for('login'), follow_redirects=True, data={'username': USERNAME, 'password': PASSWORD}) assert_logged_in(resp) assert USERNAME == current_user.name assert new_email == current_user.email
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.about_me = form.about_me.data db.session.add(current_user) flash('Your profile has been updated.') return redirect(url_for('.user', username=current_user.username)) form.name.data = current_user.name form.location.data = current_user.location form.about_me.data = current_user.about_me return render_template('edit_profile.html', form=form)
def auth_audit_log(response): """On deployment remove the ``crossdomain`` decorator""" try: jdata = json.loads(request.data.decode()) if 'password' in jdata: jdata['password'] = '*********' jdata_str = json.dumps(jdata) except ValueError: jdata_str = '' kwargs = { 'module': auth.name, 'user': current_user.name, 'email': current_user.email, 'action': _HTTP_METHOD_TO_AUDIT_MAP[request.method.lower()], 'data': addslashes(jdata_str), 'url': request.url, 'endpoint': request.endpoint, 'ip': request.remote_addr, 'status': response.status, 'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') } entry = [] for k, v in kwargs.items(): entry.append('{0!s}="{1!s}"'.format(k, v)) entry = ' '.join(entry) current_app.audit_log.info('{0!s}'.format(entry)) return response
def api_audit_log(response): """Saves information about the request in the ``audit_log`` :param response: Server :class:`~flask.Response` :return: :class:`~flask.Response` """ kwargs = { 'module': api.name, 'user': current_user.name, 'email': current_user.email, 'action': _HTTP_METHOD_TO_AUDIT_MAP[request.method.lower()], 'data': addslashes(request.data.decode()), 'url': request.url, 'endpoint': request.endpoint, 'ip': request.remote_addr, 'status': response.status, 'timestamp': datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S') } if not request.view_args and request.method.lower() == 'put': kwargs['action'] = _HTTP_METHOD_TO_AUDIT_MAP['post'] entry = [] for k, v in kwargs.items(): entry.append('{0!s}="{1!s}"'.format(k, v)) entry = ' '.join(entry) current_app.audit_log.info('{0!s}'.format(entry)) return response
def edit_profile(): form = EditProfileForm() if request.method == 'GET': return render_template('edit-profile.html', form=form, user=current_user) else: current_user.name = form.name.data current_user.location = form.location.data current_user.about_me = form.about_me.data db.session.add(current_user) flash(u"?????????") return redirect(url_for('main.user', username=current_user.username))
def edit_profile_admin(id): user = User.query.get_or_404(id) form = EditProfileAdminForm(user=user) if request.method == 'GET': return render_template('user.html', username=user.username) else: user.email = form.email.data user.username = form.username.data user.confirmed = form.confirmed.data user.name = form.name.data user.location = form.location.data user.about_me = form.about_me.data db.session.add(user) flash(u'????????') return redirect(url_for('main.user', username=user.username))
def login(): """Login to application.""" form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(name=form.name.data).first() if user: user.authenticated = True db.session.add(user) db.session.commit() login_user(user, remember=True) flash("Login success") return redirect(request.args.get('next') or "/index") return redirect('/login') return render_template('about.html', form=form, title="Log in")
def get_index(): # If a bibtex is being posted, process: if request.method == 'POST': if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('No selected file') return redirect(request.url) if file: bibtexstr = file.read().decode("utf8") if file.filename[-4:] == ".bib": add_bibtex_string(bibtexstr) elif file.filename[-4:] == ".xml": add_xml_string(bibtexstr) flash("{} has been added to database.".format(file.filename)) return redirect(request.url) # then, display page: form = ExtendedSearchForm() activity = db.session.query(Event).all() events = [] # Store events in a dictionnary for p in activity: date = datetime.datetime.fromtimestamp(p.time).strftime("%d/%m %H:%M") events.append({ "author": p.author, "article": p.article, "date": date, "type":p.event }) num_entries = db.session.query(BiblioEntry).count() return render_template("index.html", title="Index", form=form, user=current_user.name, events=events[::-1], num_entries=num_entries)
def follow_request(): form = ExtendedSearchForm() if form.validate_on_submit(): print(form.source.data) if form.source.data == "local": redirect("/biblio/search", code=307) elif form.source.data == "hal": redirect("/hal/"+form.name.data) else: flash("Not implemented yet") return redirect("/index")
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name = form.name.data current_user.location = form.location.data current_user.about_me = form.about_me.data db.session.add(current_user._get_current_object()) db.session.commit() flash('Your profile has been updated.') return redirect(url_for('.user', username=current_user.username)) form.name.data = current_user.name form.location.data = current_user.location form.about_me.data = current_user.about_me return render_template('edit_profile.html', form=form)
def post(self): content = json.loads(json.dumps(request.get_json(force = True))) email = content['email'] password = content['password'] registerTime = content['registerTime'] name = content['name'] result = User.register(email = email, name = name, password = password, registerTime = registerTime) if result == False: return {"ERROR": "The email is already registered"} else: return {'SUCCESS': 'Register Successfully'}
def post(self): content = json.loads(json.dumps(request.get_json(force = True))) name = content['username'] current_user.changeUsername(name = name) return {'SUCCESS': 'Username Changed'}
def put(self): JSON = json.loads(json.dumps(request.get_json(force = True))) url = JSON['url'] userID = current_user.email name = current_user.name content = JSON['content'] time = str(datetime.datetime.now()) comment = Comment(ID = userID, name = name, content = content, time = time) check = mongo.db.comments.find({'_id': url}) if check.count() > 0: mongo.db.comments.update({'_id': url}, {'$push': {'comments': comment.toDict()}}) else: mongo.db.comments.insert({'_id': url, 'comments': [comment.toDict()]}) return {'SUCCESS': 'New Comment Updated'}
def utility_processor(): # noqa: D202 """Define funcions callable form Jinja2 using application context.""" def onboarded_organisations(): return list( Organisation.select(Organisation.name, Organisation.tuakiri_name).where( Organisation.confirmed.__eq__(True))) def orcid_login_url(): return url_for("orcid_login", next=get_next_url()) def tuakiri_login_url(): _next = get_next_url() if EXTERNAL_SP: session["auth_secret"] = secret_token = secrets.token_urlsafe() _next = url_for("handle_login", _next=_next, _external=True) login_url = append_qs(EXTERNAL_SP, _next=_next, key=secret_token) else: login_url = url_for("handle_login", _next=_next) return login_url return dict( orcid_login_url=orcid_login_url, tuakiri_login_url=tuakiri_login_url, onboarded_organisations=onboarded_organisations, )
def read_uploaded_file(form): """Read up the whole content and deconde it and return the whole content.""" raw = request.files[form.file_.name].read() for encoding in "utf-8", "utf-8-sig", "utf-16": try: return raw.decode(encoding) except UnicodeDecodeError: continue return raw.decode("latin-1")
def inaccessible_callback(self, name, **kwargs): """Handle access denial. Redirect to login page if user doesn"t have access.""" return redirect(url_for("login", next=request.url))
def user_organisations(user_id): """Manage user organisaions.""" user_orgs = (Organisation.select( Organisation.id, Organisation.name, (Organisation.tech_contact_id == user_id).alias("is_tech_contact"), UserOrg.is_admin).join( UserOrg, on=((UserOrg.org_id == Organisation.id) & (UserOrg.user_id == user_id))) .naive()) return render_template("user_organisations.html", user_orgs=user_orgs)
def email_template(): """Manage organisation invitation email template.""" org = current_user.organisation form = EmailTemplateForm(obj=org) default_template = app.config.get("DEFAULT_EMAIL_TEMPLATE") if form.validate_on_submit(): if form.prefill.data or form.reset.data: form.email_template.data = default_template elif form.cancel.data: pass elif form.send.data: logo = org.logo if form.email_template_enabled.data else None utils.send_email( "email/test.html", recipient=(current_user.name, current_user.email), reply_to=(current_user.name, current_user.email), cc_email=(current_user.name, current_user.email), sender=(current_user.name, current_user.email), subject="TEST EMAIL", org_name=org.name, logo=url_for("logo_image", token=logo.token, _external=True) if logo else None, base=form.email_template.data if form.email_template_enabled.data else default_template) elif form.save.data: # form.populate_obj(org) org.email_template = form.email_template.data org.email_template_enabled = form.email_template_enabled.data org.save() flash("Saved organisation email template'", "info") return render_template("email_template.html", form=form)
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name=form.name.data current_user.location=form.location.data current_user.about_me=form.about_me.data db.session.add(current_user) flash('Your profile has been updated.') return redirect(url_for('.user', username=current_user.username)) form.name.data=current_user.name form.location.data=current_user.location form.about_me.data=current_user.about_me return render_template('edit_profile.html', form=form)
def edit_profile(): form = EditProfileForm() if form.validate_on_submit(): current_user.name=form.name.data current_user.location = form.location.data current_user.about_me=form.about_me.data db.session.add(current_user) flash('Your porfile has been updated.') return redirect(url_for('.user', username=current_user.username)) form.name.data=current_user.name form.location.data=current_user.location form.about_me.data=current_user.about_me return render_template('edit_profile.html', form=form)
def profile(): user = current_user terms = db.or_(PointLog.sender_id==user.id, PointLog.receiver_id==user.id) query = PointLog.query.filter(terms).order_by(PointLog.created_at.desc()) form = ProfileForm(request.form, name=user.name, bio=user.bio) if request.method == 'POST' and form.validate_on_submit(): current_user.name = form.name.data current_user.bio = form.bio.data db.session.commit() flash('Profile updated successfully') return render_template('settings/profile.html', form=form, sidebar_active='profile', point_logs=query.limit(20))
def user_github(): if request.method == 'POST' and current_user.is_authenticated: action = request.form.get('action') if action == 'unlink': current_user.github_id = None current_user.github_token = None current_user.github_username = None db.session.commit() repos = Repository.query.filter_by( owner_id=current_user.id, imported_from='GitHub' ).order_by(Repository.name).all() integration = github_helper.get_integration() return render_template('settings/github.html', integration=integration, repos=repos, sidebar_active='github')
def user_profile_posts(username, page=1): # query user from the database by username # if user doesn't exsist throw 404 error user = User.query.filter_by(name=username).first_or_404() posts = user.posts.order_by(Post.id.desc()) per_page = app.config["POSTS_PER_PAGE"] paginated_posts = posts.paginate(page, per_page) next_url = url_for("posts.user_profile_posts", page=page + 1, username=user.name ) prev_url = url_for("posts.user_profile_posts", page=page - 1, username=user.name ) if current_user.is_authenticated and current_user.name == user.name: user_profile = True else: user_profile = False return render_template("user_profile_posts.html", user=user, user_profile=user_profile, posts=paginated_posts, title=user.name, next_url=next_url, prev_url=prev_url )
def following(username): user = User.query.filter_by(name=username).first_or_404() if current_user.is_authenticated and current_user.name == user.name: user_profile = True else: user_profile = False users = user.following.all() return render_template("user_following_and_followers.html", user=user, users=users, user_profile=user_profile, title="{} followings".format(user.name) )
def followers(username): user = User.query.filter_by(name=username).first_or_404() if current_user.is_authenticated and current_user.name == user.name: user_profile = True else: user_profile = False users = user.followers.all() return render_template("user_following_and_followers.html", user=user, user_profile=user_profile, users=users, followers=True, title="{} followers".format(user.name) )