• 完成个人中心—导航标签


      1. 个人中心—视图函数带标签页面参数tag
        @app.route('/usercenter/<user_id>/<tag>')
        def usercenter(user_id, tag):
           if tag == ‘1':
               return render_template('usercenter1.html', **context)

      2. 个人中心—导航标签链接增加tag参数
        <li role=“presentation”><a href=“{{ url_for(‘usercenter’,user_id = user.id,tag = ‘1’) }}">全部问答</a></li>

      3. 个人中心—有链接到个人中心页面的url增加tag参数
         <a href="{{ url_for('usercenter',user_id = session.get('userid'), tag=1) }}">{{ session.get('user') }}</a>
      4. from flask import Flask,render_template,request,redirect,url_for,session
        from flask import Flask
        from flask_sqlalchemy import SQLAlchemy
        import config
        from functools import wraps
        from datetime import datetime
        
        app = Flask(__name__)
        #app.config['SECRET_KEY'] = '1234567'
        app.config.from_object(config)
        db = SQLAlchemy(app)
        
        class User(db.Model):
            __tablename__ = 'user_test'
            id=db.Column(db.Integer,primary_key=True,autoincrement=True)
            username=db.Column(db.String(20),nullable=False)
            password = db.Column(db.String(20), nullable=False)
            nickname = db.Column(db.String(20))
            tel = db.Column(db.String(20))
        
        class Question(db.Model):
            __tablename__ = 'question'
            id=db.Column(db.Integer,primary_key=True,autoincrement=True)
            title = db.Column(db.String(100),nullable=False)
            detail = db.Column(db.Text,nullable=False)
            creat_time = db.Column(db.DateTime,default=datetime.now)
            author_id = db.Column(db.Integer,db.ForeignKey('user_test.id'))
            author = db.relationship('User',backref=db.backref('question'))
        
        class Comment(db.Model):
            __tablename__ = 'comment'
            id = db.Column(db.Integer, primary_key=True, autoincrement=True)
            author_id = db.Column(db.Integer,db.ForeignKey('user.id'))
            question_id = db.Column(db.Integer,db.ForeignKey('question.id'))
            detail = db.Column(db.Text, nullable=False)
            creat_time = db.Column(db.DateTime, default=datetime.now)
            question=db.relationship('Question',backref=db.backref('comments',order_by=creat_time.desc))
            author = db.relationship('User', backref=db.backref('comment'))
        
        
        
        #db.create_all()
        
        
        #user = User(username = 'mis1',password = '124', nickname='wk')
        #db.session.add(user)
        #db.session.commit()
        
        
        
        #user = User.query.filter(User.username == 'mis1234').first()
        #print(user)
        #print(user.id,user.username)
        
        
        #user = User.query.filter(User.username == 'mis1234').first()
        #user.password = '123'
        #db.session.commit()
        
        
        # user = User(username = 'wkkkkkk',password = '123456', nickname='kk')
        # db.session.add(user)
        # db.session.commit()
        
        
        #user = User.query.filter(User.username == 'mis1234').first()
        #db.session.delete(user)
        #db.session.commit()
        
        
        
        
        @app.route('/')
        def index():
            context={
                'questions':Question.query.all()
            }
            return render_template('index.html',**context)
        
        
        @app.route('/detail/<question_id>')
        def detail(question_id):
            return render_template('detail.html',ques = question_id)
        
        
        
        
        
        
        
        @app.route('/login/',methods=['GET','POST'])
        def login():
            if request.method == 'GET':
                return render_template('login.html')
            else:
                usern = request.form.get('uname')
                passw = request.form.get('upass')
                user = User.query.filter(User.username==usern).first()
                if user:
                    if user.password == passw:
                        session['user'] = usern;
                        return redirect(url_for('index'))
                    else:
                        return 'password error!'
                else:
                    return 'username is not exister!'
        
        
        
        @app.route('/register/',methods=['GET','POST'])
        def register():
            if request.method =='GET':
                return  render_template('register.html')
            else:
                usern = request.form.get('uname')
                teln = request.form.get('number')
                passw = request.form.get('upass')
                user = User.query.filter(User.username==usern).first()
                if user:
                    return 'username existed'
                else:
                    user1= User(username=usern,tel=teln,password=passw)
                    db.session.add(user1)
                    db.session.commit()
                    return redirect(url_for('login'))
        
        
        @app.context_processor
        def mycontext():
            usern = session.get('user')
            if usern:
                return{'username':usern}
            else:
                return {}
        
        def loginFirst(func):
            @wraps(func)
            def wrapper(*args,** kwargs):
                if session.get('user'):
                    return func(*args,** kwargs)
                else:
                    return redirect(url_for('login'))
            return wrapper
        
        
        
        
        
        @app.route('/question/',methods=['GET','POST'])
        @loginFirst#需要登录装饰器
        def question():
            if request.method =='GET':
                return  render_template('question.html')
            else:
                title = request.form.get('title')
                detail = request.form.get('detail')
                author_id = User.query.filter(User.username==session.get('user')).first().id
                author_id=user.id
                question = Question(title=title,detail=detail,author_id=author_id)
                question.author=user
        
                db.session.add(question)
                db.session.commit()
            return redirect(url_for('index'))
        
        @app.route('/detail/<question_id>',methods=['GET','POST'])
        def detail(question_id):
            quest=Question.query.filter(Question.id==question_id).first()
            return  render_template('detail.html',ques=quest)
        
        @app.route('/comment/',methods=['POST'])
        def comment():
            comment=request.form.get('nem_comment')
            ques_id=request.form.get('question_id')
            auth_id=User.query.filter(User.username==session.get('user')).first().id
            comm=Comme(author_id=auth_id,question_id=ques_id ,detail=comment)
            db.session.add(comm)
            db.session.commit()
            return redirect(url_for('detail',question_id=ques_id))
        
        
        
        @app.route('/usercenter/<user_id>/<tag>')
        @login_re
        def usercenter(user_id,tag):
            user=User.query.filter(User.id==user_id).first()
            context={
                'user':user
            }
            if tag=='1':
                return render_template('usercenter1.html',**context)
            elif tag =='2':
                return render_template('usercenter2.html ',**context)
            else:
                return render_template('usercenter3.html',**context)
            return render_template('user1.html',**context)
        
        
        
        
        
        if __name__ == '__main__':
            app.run(debug=True)

        userbase.html

      5. {% extends"base.html" %}
        {% block title %}个人中心{% endblock %}
        {% block head %}
            <style>
                .nav_ul li{
                    list-style: none;
                    float: left;
                    margin: 15px;
        
                }
            </style>
        {% endblock %}
        {% block main %}
        <ul class="nav_ul-tabs">
             <li role="presentation"><a href="{{ url_for('usercenter',user_id=user.id,tag='1') }}">全部问答</a> </li>
             <li role="presentation"><a href="{{ url_for('usercenter',user_id=user.id,tag='2') }}">全部评论</a> </li>
             <li role="presentation"><a href="{{ url_for('usercenter',user_id=user.id,tag='3') }}">个人资料</a> </li>
        </ul>
            {% block user %}{% endblock %}
        {% endblock %}

        index.html

      6. {% extends 'detail.html' %}
        {% block title %}首页{% endblock %}
        
        {% block main %}
            <img sr="{{ url_for('staic',filename='images/qalogo.png') }}" alt="qa">
            <ul class="list-group" style="....">
            {% for foo in question %}
                <li class="list-group-items">
                <span class="glyphicon glyphicon-leaf" aria-hidden="="true></span>
                <a href="{{ url_for('detail',question_id =foo.id) }}">{{ foo.title }}</a>
                <p style="">{{ foo.detail }}</p>
                <span class="glyphicon glyphicon-user" aria-hidden="true"></span>
                <a href="{{ url_for('usercenter',user_id=foo.author_id,tag=1) }}">{{ foo.author.username }}评论:({{ foo.comments|length }})</a>
                <span class="badge">{{ foo.creat_time }}</span>
        
                </li>
            {% endfor %}
        
            </ul>
        
        {% endblock %}

        detail.html

      7. {% extends 'base.html' %}
        {%  block title %}问答详情{% endblock %}
        {% block main %}
        <div class="page-header">
            <h3>{{ ques.title }}<br><small>{{ ques.author.username }} <span class="badge">{{ ques.creat_time }}</span> </small></h3>
        
        </div>
        <p class="lead">{{ ques.detail }}</p>
        <hr>
        <form action="{{ url_for('comment') }}" method="post" style="..."...></form>
            <div class="form-group">
            <textarea name ="new_comment" class="form-control" rows="3"id="new-comment" placeholder="write your comment"></textarea>
            <input type="hidden" name="question_id" value="{{ ques.id }}">
            </div>
            <botton type="submit" class="btn btn-default">发送</botton>
            </form>
        
        <h4>评论:({{ ques.comments|length }}</h4>
        
        <ul class="list-group" style=""></ul>
            {% for foo in ques.comments %}
            <li class="list-group-item">
            <span class="glyphicon glyphicon-heart-empty" aria-hidden="true"></span>
            <a href="{{ url_for('usercenter',user_id=foo.author.id,tag=1 )}}">{{ foo.author.username }}</a>
                <span class="badge">{{ foo.create_time }}</span>
                <p style="align-content: center">{{ foo.detail }}</p>
            </li>
        {%  endfor %}
        </ul>

        base.html

      8. <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body id="mybody">
          <nav class="navbar navbar-default">
              <div class="navbar-header">
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
                <li class="active"><a href="{{ url_for('index') }}">首页<span class="sr-only"></span> </a> </li>
                <li><a href="{{ url_for('question') }}">发布问答</a> </li>
            </ul>
            <form action="{{ url_for('search') }}" method="get" class="navbar-form navbar-left">
                <div class="form-group">
                    <input name="q" type="text" class="form-control" placeholder="请输入关键词">
        
                </div>
                <botton type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search" aria-hidden="true"></span> 查找 </botton>
        
            </form>
            <ul class="nav navbar-nav navbar-right">
                {% if user %}
                    <li><a href="{{ url_for('usercenter',user_id =session.get('userid'),tag=1) }}">{{ session.get('user') }}</a> </li>
                    <li><a href="{{ url_for('logout') }}">注销</a> </li>
                    {% else %}
                    <li><a href="{{ url_for('login') }}">登录</a> </li>
                    <li><a href="{{ url_for('register') }}">注册</a> </li>
        
                {% endif %}
            <li><img id="on_off"  onclick="mySwitch()" src="http://www.runoob.com/images/pic_bulbon.gif"  width="20" height="20">></li>
            </ul>
            </div>
        </div>
        </nav>
        
        </body>
        </html>
  • 相关阅读:
    学习进度三
    开课博客之个人介绍
    个人作业--数组
    学习进度二
    开学第一次测试
    实现点击不同的按钮加载不同的css
    Web存储
    HTML5(常用的表单控件)
    JS(获得当前时间并且用2015-01-01格式表示)
    JS(event事件)
  • 原文地址:https://www.cnblogs.com/123hyf/p/8067329.html
Copyright © 2020-2023  润新知