如何处理从表单获得的值并使用该值给出结果

时间:2019-04-25 18:35:38

标签: python jquery flask flask-wtforms

我正在尝试制作一个测验应用程序,该应用程序允许用户回答问题并获得分数,这些问题存储在数据库中。我在重新获得分数时遇到问题,当我单击提交以回答问题时,我得到了AttributeError:'NoneType'对象没有属性'score'

我搜索是否有人做了类似的事情,然后想到了使用jquery来获取用户ID和用户输入的值

这是我的html页面,用于显示问题和多项选择:

<head>
        <!-- Required meta tags -->
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="{{url_for('static', filename='jquery.js') }}">\x3C/script>')</script>

    <script type='text/javascript' src="{{ url_for('static', filename='scoring.js') }}"></script>


        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css">
        <!-- Compiled and minified JavaScript -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>

    </style>
    <!-- Required for the page -->
    <script type='text/javascript'>

        //sets the global variable to the prefix to the root of the application
        $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
        //Calls the answer checking script with the variable argument
        $(document).ready(function() {
            $('select').material_select();
            $(".button-collapse").sideNav(); 
            startScript({{ current_user.id }}, {{ users[0].score }});
        });
    </script>

        <title>Hello, world!</title>
    </head>



        <body>
            <h5 class="center-align">Answer the Questions</h5>
            <form action="http://localhost:5000/info" method='POST'>
                {{ form.csrf_token }}


                    {% for computersystemsq in computersystemsq %}
                    {% for computersystemsm in computersystemsm %}

                        <div class="row">
                                <div class="col s12">
                                    {{ computersystemsq.question }}
                                </div>
                        </div>
                        <div class="{{ computersystemsm.id }}"></div>
                                <div class="row">
                                    <div class="col s6">
                                        A: {{ computersystemsm.wrong_answer1 }}
                                    </div>
                                    <div class="col s6">
                                        B: {{ computersystemsm.wrong_answer2 }}
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col s6">
                                        C: {{ computersystemsm.answer }}
                                    </div>
                                </div>
                                    <div class="row">
                                            <div class="input-field col s6">
                                                {{ form.options( class= computersystemsm.id ) }}
                                                <label for="options">Select an Option:</label>                  
                                            </div>
                                    </div>
                                    <button class="btn waves-effect waves-light" type="submit" id="{{ computersystemsm.id }}">mark</button>
                <br>
                        </div>  
                    {% endfor %}
                    {% endfor %}

这是为用户提供分数并将该分数存储回数据库的评分代码:

function startScript( current_userId) {
    $( document ).ready( readyFunction );

    function readyFunction() {
        $("button").click( function(event) {
            var url = $SCRIPT_ROOT + '/info';


            var selectedId = $(this).attr('id');
            var selectedValue = $("select." + selectedId).val();
            $.getJSON( url, {
                id: selectedId,
                value: selectedValue,
                user_id: current_userId
                },
                function (data) {
                    //Doing the checking and all on server side
                    var scoreElement = document.getElementById("studentusersscore");
                    scoreElement.text = 'Your SCORE is ' + data.score;
                    $("." + selectedId).hide(1000);

                }
            );
            event.preventDefault();



        });
    }
}

这是获取分数并将其存储回用户表的网址:

@app.route("/info",methods=['POST'])
def info():
    id = request.args.get('id',0,type=int)
    value = request.args.get('value',0,type=str)
    userId = request.args.get('user_id',0,type=int)


    presentUser = User.query.get( userId )
    presentScore = presentUser.score
    computersystemsm=ComputerSystemsMultipleChoices.query.filter( ComputerSystemsMultipleChoices.id == id ).all()

    if computersystems[0].answer==value:
        presentScore=presentScore + 1
        presentUser.score=presentScore
        correct=1

    else:
        presentScore=presentScore -1
        presentUser.score=presentScore
        correct=0

    return jsonify(score = presentScore, correct = correct)

跟踪:

AttributeError
AttributeError: 'NoneType' object has no attribute 'score'

Traceback (most recent call last)
File "c:\users\dami\envs\compsci\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "c:\users\dami\envs\compsci\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "c:\users\dami\envs\compsci\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "c:\users\dami\envs\compsci\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "c:\users\dami\envs\compsci\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "c:\users\dami\envs\compsci\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "c:\users\dami\envs\compsci\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "c:\users\dami\envs\compsci\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "c:\users\dami\envs\compsci\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
        self.try_trigger_before_first_request_functions()
        try:
            request_started.send(self)
            rv = self.preprocess_request()
            if rv is None:
                rv = self.dispatch_request()
        except Exception as e:
            rv = self.handle_user_exception(e)
        return self.finalize_request(rv)

    def finalize_request(self, rv, from_error_handler=False):
File "c:\users\dami\envs\compsci\lib\site-packages\flask\app.py", line 1799, in dispatch_request
        # request came with the OPTIONS method, reply automatically
        if getattr(rule, 'provide_automatic_options', False) \
           and req.method == 'OPTIONS':
            return self.make_default_options_response()
        # otherwise dispatch to the handler for that endpoint
        return self.view_functions[rule.endpoint](**req.view_args)

    def full_dispatch_request(self):
        """Dispatches the request and on top of that performs request
        pre and postprocessing as well as HTTP exception catching and
        error handling.
File "C:\Users\Dami\dev\compsci\revision_website\quiz.py", line 358, in info
presentScore = presentUser.score
AttributeError: 'NoneType' object has no attribute 'score'

总的来说,我想让每个问题的用户分数都返回给他们,并且应该将分数添加到表格中以存储他们对或错的每个问题。

0 个答案:

没有答案