首页 > 解决方案 > 如何处理从表单中获得的值并使用该值给出结果

问题描述

我正在尝试制作一个测验应用程序,它允许用户回答问题并取回他们的分数,这些问题存储在数据库中。我在取回分数时遇到问题,当我单击提交回答问题时,我得到一个 AttributeError:'NoneType' object has no attribute '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();



        });
    }
}

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

@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'

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

标签: pythonjqueryflaskflask-wtforms

解决方案


推荐阅读