Аватар для Flask

Я создаю приложение Flask, и я не могу заставить Аватар работать, когда пользователь обновляет свой профиль. Все остальное работает, включая имя, местоположение и обо мне, но когда я пытаюсь загрузить изображение, ничего не происходит. Любая помощь здесь была бы чрезвычайно оценена.

Вот мои models.py:

from flask_mongoengine.wtf import model_form
from mongoengine import Document, StringField, EmailField, 
ReferenceField, IntField, DateTimeField, 
BooleanField, DictField, ListField, EmbeddedDocument, 
EmbeddedDocumentListField, FloatField, FileField
from datetime import datetime 
from werkzeug.security import generate_password_hash, 
check_password_hash
from flask import request, current_app, url_for 
from hashlib import md5
from app import db
from app import login_manager
from flask import request, current_app
from flask_login import UserMixin, AnonymousUserMixin  
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from hashlib import md5
from markdown import markdown
import bleach
from datetime import datetime 
import random

class User(db.Model): 
    __tablename__ = 'users'
    __table_args__ = {'extend_existing': True} 
    id = db.Column(db.Integer, primary_key = True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    #confirmation_code = db.Column(db.Sting(200))

    role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) 


    confirmed = db.Column(db.Boolean, default=False) 

    posts = db.relationship('Post', backref='author', lazy='dynamic') 
    comments = db.relationship('Comment', backref='author', 
    lazy='dynamic') 

    name = db.Column(db.String(64))
    location = db.Column(db.String(64))
    about_me = db.Column(db.Text())
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    avatar_hash = db.Column(db.String(32))

    def gravatar_hash(self):
        return hashlib.md5(self.email.lower().encode('utf- 
        8')).hexdigest()

    def gravatar(self, size=100, default='identicon', 
    rating='g'):
        url = 'https://secure.gravatar.com/avatar'
        hash = self.avatar_hash 
        #hash = self.avatar_hash or self.gravatar_hash()
        return '{url}/{hash}?s={size}&d={default}&r= 
        {rating}'.format(
        url=url, hash=hash, size=size, default=default, 
        rating=rating)

Вот view.py:

@server.route('/edit-profile', methods=['GET', 'POST'])
@login_required
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) 
        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)

Вот form.py:

class EditProfileForm(Form): 
    name = StringField('Real Name', validators=[Length(0, 
    64)])
    location = StringField('Location', validators= 
    [Length(0, 64)])
    about_me = TextAreaField('About Me')
    avatar_hash = FileField() 
    submit = SubmitField('Submit')
    #photo = FileField() 

Вот edit_profile.html:

{% extends "base.html" %}

{% import "bootstrap/wtf.html" as wtf %} 

{% block title %} Deplorable Snowflake- Edit Profile {% 
endblock %}

{% block content %} 

<div>

<h1> Edit Your Profile </h1>

{{wtf.quick_form(form)}}

</div>

{% endblock %}

Вот user.html:

{% extends "base.html" %}

{% block content %}

<div class ="page-header">
<h1> {{ user.username }} </h1>
{% if user.name or user.location %}
<p>
{% if user.name %} {{ user.name }} {% endif %}
{% if user.location %}
    From <a href="http://maps.google.com/?q={{ 
user.location }}">
    {{ user.location }}
    </a>
{% endif %}
</p>
{% endif %}

{% if current_user.is_administrator %}
<p> <a href="mailto:{{ user.email }}"> {{ user.email }} 
</a> 
</p>
{% endif %}

{% if user.about_me %}<p> {{ user.about_me }} </p> 
{% endif %}
  {% if user == current_user %}
  <a class="btn btn-default" href="{{ 
  url_for('edit_profile') }}">
  Edit Profile
  </a>
  {% endif %}

  <img class="img-rounded profile-thumbnail" src ="{{ 
  user.gravatar(size=256) }}"> 


  <h3>Posts by {{ user.username }} </h3> 
  {% include '_posts.html' %}


  </div>


  {% endblock %}

python,flask,avatar,

-1

Ответов: 0

Аватар для Flask

Я создаю приложение Flask, и я не могу заставить Аватар работать, когда пользователь обновляет свой профиль. Все остальное работает, включая имя, местоположение и обо мне, но когда я пытаюсь загрузить изображение, ничего не происходит. Любая помощь здесь была бы чрезвычайно оценена.

Вот мои models.py:

from flask_mongoengine.wtf import model_form
from mongoengine import Document, StringField, EmailField, 
ReferenceField, IntField, DateTimeField, 
BooleanField, DictField, ListField, EmbeddedDocument, 
EmbeddedDocumentListField, FloatField, FileField
from datetime import datetime 
from werkzeug.security import generate_password_hash, 
check_password_hash
from flask import request, current_app, url_for 
from hashlib import md5
from app import db
from app import login_manager
from flask import request, current_app
from flask_login import UserMixin, AnonymousUserMixin  
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from hashlib import md5
from markdown import markdown
import bleach
from datetime import datetime 
import random

class User(db.Model): 
    __tablename__ = 'users'
    __table_args__ = {'extend_existing': True} 
    id = db.Column(db.Integer, primary_key = True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    #confirmation_code = db.Column(db.Sting(200))

    role_id = db.Column(db.Integer, db.ForeignKey('roles.id')) 


    confirmed = db.Column(db.Boolean, default=False) 

    posts = db.relationship('Post', backref='author', lazy='dynamic') 
    comments = db.relationship('Comment', backref='author', 
    lazy='dynamic') 

    name = db.Column(db.String(64))
    location = db.Column(db.String(64))
    about_me = db.Column(db.Text())
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
    avatar_hash = db.Column(db.String(32))

    def gravatar_hash(self):
        return hashlib.md5(self.email.lower().encode('utf- 
        8')).hexdigest()

    def gravatar(self, size=100, default='identicon', 
    rating='g'):
        url = 'https://secure.gravatar.com/avatar'
        hash = self.avatar_hash 
        #hash = self.avatar_hash or self.gravatar_hash()
        return '{url}/{hash}?s={size}&d={default}&r= 
        {rating}'.format(
        url=url, hash=hash, size=size, default=default, 
        rating=rating)

Вот view.py:

@server.route('/edit-profile', methods=['GET', 'POST'])
@login_required
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) 
        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)

Вот form.py:

class EditProfileForm(Form): 
    name = StringField('Real Name', validators=[Length(0, 
    64)])
    location = StringField('Location', validators= 
    [Length(0, 64)])
    about_me = TextAreaField('About Me')
    avatar_hash = FileField() 
    submit = SubmitField('Submit')
    #photo = FileField() 

Вот edit_profile.html:

{% extends "base.html" %}

{% import "bootstrap/wtf.html" as wtf %} 

{% block title %} Deplorable Snowflake- Edit Profile {% 
endblock %}

{% block content %} 

<div>

<h1> Edit Your Profile </h1>

{{wtf.quick_form(form)}}

</div>

{% endblock %}

Вот user.html:

{% extends "base.html" %}

{% block content %}

<div class ="page-header">
<h1> {{ user.username }} </h1>
{% if user.name or user.location %}
<p>
{% if user.name %} {{ user.name }} {% endif %}
{% if user.location %}
    From <a href="http://maps.google.com/?q={{ 
user.location }}">
    {{ user.location }}
    </a>
{% endif %}
</p>
{% endif %}

{% if current_user.is_administrator %}
<p> <a href="mailto:{{ user.email }}"> {{ user.email }} 
</a> 
</p>
{% endif %}

{% if user.about_me %}<p> {{ user.about_me }} </p> 
{% endif %}
  {% if user == current_user %}
  <a class="btn btn-default" href="{{ 
  url_for('edit_profile') }}">
  Edit Profile
  </a>
  {% endif %}

  <img class="img-rounded profile-thumbnail" src ="{{ 
  user.gravatar(size=256) }}"> 


  <h3>Posts by {{ user.username }} </h3> 
  {% include '_posts.html' %}


  </div>


  {% endblock %}
0-1питон, колба, аватар,
Похожие вопросы