flask笔记:7:用户资料信息页和头像

用户信息页
创建一个新的视图函数 app/views.py
from app import app,db,lm,models
from flask import render_template,flash,redirect,url_for,session,request,g
from .forms import LoginForm
from .models import User
from flask.ext.login import login_user,logout_user,current_user,login_required

@lm.user_loader
def load_user(id):
    return User.query.get(int(id))

@app.before_request
def before_request():
    g.user = current_user

@app.route('/')
@app.route('/index')
@login_required
def index ():
    user=g.user
    posts=[
            {'author':{'nickname':'John'},
             'body':'Beautiful day in Portland!'},
            {'author':{'nickname':'Susan'},
             'body':'The Avengers movie was so cool!'}
           ]
    return render_template("index.html",
    title="Home",
    user=user,
    posts=posts)

@app.route('/login', methods = ['GET', 'POST'])
def login():
    if g.user is not None and g.user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        if models.User.query.filter_by(nickname=form.openid.data).first():
            user = User.query.filter_by(nickname=form.openid.data).first_or_404()
            login_user(user)
            return redirect(url_for('index'))
        else:
            return render_template('login.html',
        title = 'Sign In',
        error='[NO]',
        form = form)
    return render_template('login.html',
        title = 'Sign In',
        form = form)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/user/<nickname>')
@login_required
def user(nickname):
    user=User.query.filter_by(nickname=nickname).first()
    if user==None:
        flash('user'+nickname+'not found!')
        return redirect(url_for('index'))
    posts=[
        {'author':user,'body':'Test post #1 !!!'},
        {'author':user,'body':'Test post #2 !!!'}
    ]
    return render_template('user.html',
        user=user,
        posts=posts
        )
#根据nickname区分用户,进入不同的用户界面



新增视图模板 app/templates/user.html
{% extends "base.html" %}
{% block content %}
<h1>User:{{user.nickname}} </h1>
<hr>
{% for post in posts %}
<p>
    {{post.author.nickname}} says:<b>{{post.body}}</b>
</p>
{% endfor %}
{% endblock %}


修改base模板 app/templates/base.html
  
<html>
    <head>
        {% if title%}
        <title>{{title}} - mybolg</title>
        {% else%}
        <title>Welcome - myblog</title>
        {% endif %}
    </head>
    <body>
        <div>MyBlog:<a href="/index">Home</a>
        {% if g.user.is_authenticated %}
        |<a href="{{url_for('user',nickname = g.user.nickname)}}">Your Profile</a>
        |<a href="{{url_for('logout')}}">Logout</a>
        {% endif %}
        </div>
        <hr>
        {% with messages = get_flashed_messages() %}
        {% if messages %}
        <ul>
            {% for message in messages %}
            <li>{{message}}</li>
            {% endfor %}
        </ul>
        {% endif %}
        {% endwith %}
        {% block content %}
        {% endblock %}
    </body>
</html>

#url_for( )可以加入参数

输入正确用户名
flask笔记:7:用户资料信息页和头像_第1张图片

进入主页
flask笔记:7:用户资料信息页和头像_第2张图片

点击用户页面进入,url中显示用户名
flask笔记:7:用户资料信息页和头像_第3张图片

用户头像
在User类中添加头像位置,修改 app/models.py
from app import db
import os

sep=os.sep

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    nickname=db.Column(db.String(64),index=True,unique=True)
    email=db.Column(db.String(120),index=True,unique=True)
    posts=db.relationship('Post',backref='author',lazy='dynamic')

    def avatar(self,size):
        return sep+'static'+sep+'img'+sep+'1.jpg'+' width= '+size

    def is_authenticated (self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        try:       
            return unicode(self.id)
        except NameError:
            return str(self.id)

    def __repr__(self):
        return '<User %r>'%(self.nickname)

class Post(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    body=db.Column(db.String(140))
    timestamp=db.Column(db.DateTime)
    user_id=db.Column(db.Integer,db.ForeignKey('user.id'))
    def __repr__(self):
        return '<Post %r>'%(self.body)

#在User中自定义avatar( )头像函数,头像图片位置和大小

修改 app/templates/user.html
{% extends "base.html" %}
{% block content %}
<table>
    <tr valign='top'>
        <td><img src={{user.avatar('128')}}></td>
        <td><h1>User:{{user.nickname}} </h1></td>
    </tr>
</table>
<hr>
{% for post in posts %}
<table>
    <tr valign='top'>
        <td><img src={{user.avatar('50')}}></td>
        <td>{{post.author.nickname}}
        says:<br>{{post.body}}</td>
    </tr>
</table>
{% endfor %}
{% endblock %}



重用子模板
新建模板 app/templates/post.html
<table>
    <tr valign='top'>
        <td><img src={{user.avatar('50')}}></td>
        <td>{{post.author.nickname}}
        says:<br>{{post.body}}</td>
    </tr>
</table>


#user.avatar('50')头像和大小

修改user.html app/templates/user.html
{% extends "base.html" %}
{% block content %}
<table>
    <tr valign='top'>
        <td><img src={{user.avatar('128')}}></td>
        <td><h1>User:{{user.nickname}} </h1></td>
    </tr>
</table>
<hr>
{% for post in posts %}
{% include 'post.html' %}
{% endfor %}
{% endblock %}


#{% include 'post.html' %} include 插入一个子模板

添加头像以后
flask笔记:7:用户资料信息页和头像_第4张图片


用户简介
在模型类User中增加两个字段,最后登入时间 和 简介,修改 app/models.py
from app import db
import os

sep=os.sep

class User(db.Model):
    id = db.Column(db.Integer,primary_key=True)
    nickname=db.Column(db.String(64),index=True,unique=True)
    email=db.Column(db.String(120),index=True,unique=True)
    posts=db.relationship('Post',backref='author',lazy='dynamic')
    about_me=db.Column(db.String(140))
    last_seen=db.Column(db.DateTime)

    def avatar(self,size):
        return sep+'static'+sep+'img'+sep+'1.jpg'+' width= '+size

    def is_authenticated (self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    def get_id(self):
        try:       
            return unicode(self.id)
        except NameError:
            return str(self.id)

    def __repr__(self):
        return '<User %r>'%(self.nickname)

class Post(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    body=db.Column(db.String(140))
    timestamp=db.Column(db.DateTime)
    user_id=db.Column(db.Integer,db.ForeignKey('user.id'))
    def __repr__(self):
        return '<Post %r>'%(self.body)


#新增字段以后,因为没有数据迁移的功能所以要删掉db文件重新建表和加数据

因为要编辑简介所以要form,修改 app/forms.py
from flask.ext.wtf import Form
from wtforms import StringField,BooleanField,TextAreaField
from wtforms .validators import DataRequired,Length

class LoginForm(Form):
    openid=StringField('openid',validators=[DataRequired()])
    remember_me=BooleanField('remember_me',default=False)

class EditForm(Form):
    nickname=StringField('nickname',validators=[DataRequired()])
    about_me=TextAreaField('about_me',validators=[Length(min=0,max=140)])
#TextAreaField( )是多行文本输入
#validators=[Length(min=0,max=140)],validators过滤器,输入最小0,最大140



新增个人简介编辑页面 app/edit.html
{% extends "base.html" %}
{% block content %}
<h1>Edit Your Prfile</h1>
<form action="" method="post" name="edit">
    {{ form.hidden_tag() }}
    <table>
        <tr>
            <td>Your nickname:</td>
            <td>{{form.nickname(size=24)}}</td>
        </tr>
        <tr>
            <td>About yourself:</td>
            <td>{{form.about_me(cols=32,rows=4)}}</td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Save Changes"></td>
        </tr>
    </table>
</form>
{% endblock %}


#form.about_me(cols=32,rows=4),设置多文本输入框的宽32,高4
#form.nickname(size=24) 输入框大小24

添加视图处理函数,修改 app/views.py
from app import app,db,lm,models
from flask import render_template,flash,redirect,url_for,session,request,g
from .forms import LoginForm, EditForm
from .models import User
from flask.ext.login import login_user,logout_user,current_user,login_required
from datetime import datetime

@lm.user_loader
def load_user(id):
    return User.query.get(int(id))

@app.before_request
def before_request():
    g.user = current_user
    if g.user.is_authenticated:
        g.user.last_seen=datetime.utcnow()
        db.session.add(g.user)
        db.session.commit()

@app.route('/')
@app.route('/index')
@login_required
def index ():
    user=g.user
    posts=[
            {'author':{'nickname':'John'},
             'body':'Beautiful day in Portland!'},
            {'author':{'nickname':'Susan'},
             'body':'The Avengers movie was so cool!'}
           ]
    return render_template("index.html",
    title="Home",
    user=user,
    posts=posts)

@app.route('/login', methods = ['GET', 'POST'])
def login():
    if g.user is not None and g.user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        if models.User.query.filter_by(nickname=form.openid.data).first():
            user = User.query.filter_by(nickname=form.openid.data).first_or_404()
            login_user(user)
            return redirect(url_for('index'))
        else:
            return render_template('login.html',
        title = 'Sign In',
        error='[NO]',
        form = form)
    return render_template('login.html',
        title = 'Sign In',
        form = form)


@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/user/<nickname>')
@login_required
def user(nickname):
    user=User.query.filter_by(nickname=nickname).first()
    if user==None:
        flash('user'+nickname+'not found!')
        return redirect(url_for('index'))
    posts=[
        {'author':user,'body':'Test post #1 !!!'},
        {'author':user,'body':'Test post #2 !!!'}
    ]
    return render_template('user.html',
        user=user,
        posts=posts
        )

@app.route('/edit',methods=["POST","GET"])
@login_required
def edit():
    form=EditForm()
    if form.validate_on_submit():
        g.user.nickname=form.nickname.data
        g.user.about_me=form.about_me.data
        db.session.add(g.user)
        db.session.commit()
        flash('Your changes have been saved!')
        return redirect(url_for('edit'))
    else:
        form.nickname.data=g.user.nickname
        form.about_me.data=g.user.about_me
    return render_template('edit.html',form=form)


#修改简介,当submit提交以后将修改的用户名和简介添加进数据库里

点击Edit进入简介页面
flask笔记:7:用户资料信息页和头像_第5张图片

用户名从数据库里读取
flask笔记:7:用户资料信息页和头像_第6张图片
数据库里nickname还是john,about_me是空


修改用户名,添加简介以后会出现flash信息
flask笔记:7:用户资料信息页和头像_第7张图片
再看数据库里用户名被修改,简介被添加
flask笔记:7:用户资料信息页和头像_第8张图片

点击个人页面会发现,用户名被修改,简介已经添加
flask笔记:7:用户资料信息页和头像_第9张图片

以上就完成了个人信息编辑展现页面,不过有点不习惯的问题
1:编辑完成后还在编辑页面,我觉得跳转到用户页面比较好
2:简介内容不能保持原始输入格式

第一个问题解决方式,修改 app/views.py
@app.route('/edit',methods=["POST","GET"])
@login_required
def edit():
    form=EditForm()
    if form.validate_on_submit():
        g.user.nickname=form.nickname.data
        g.user.about_me=form.about_me.data
        db.session.add(g.user)
        db.session.commit()
        flash('Your changes have been saved!')
        return redirect(url_for('user',nickname=g.user.nickname))
    else:
        form.nickname.data=g.user.nickname
        form.about_me.data=g.user.about_me
    return render_template('edit.html',form=form)


#修改edit函数的跳转,将原来跳转到edit,改成调到user+nickname的用户页面

第二个问题解决方式
{% extends "base.html" %}
{% block content %}
<table>
    <tr valign='top'>
        <td><img src={{user.avatar('128')}}></td>
        <td>
            <h1>User:{{user.nickname}} </h1>
            {% if user.about_me %}<pre>{{user.about_me}}</pre>{% endif %}
            {% if user.last_seen %}<p><i>Last seen on:{{user.last_seen}}</i></p>{% endif %}
            {% if user.id==g.user.id %}<p><a href="{{url_for('edit')}}">Edit</a></p>{% endif %}
        </td>
    </tr>
</table>
<hr>
{% for post in posts %}
{% include 'post.html' %}
{% endfor %}
{% endblock %}


#将用户展示页面上简介展示的标签由<p></p>改成<pre></pre>
flask笔记:7:用户资料信息页和头像_第10张图片
flask笔记:7:用户资料信息页和头像_第11张图片

你可能感兴趣的:(python,flask)