TypeError:“未定义”类型的对象不可JSON序列化

时间:2018-06-20 13:57:27

标签: javascript python flask jinja2 flask-wtforms

尝试提交表单时出现此错误。我不确定是否没有值/未定义什么,并且正在寻找指导,因为至少没有为我提供太多的见解。第一次尝试运行该页面之前,我遇到了此错误,此问题已通过将form = form放入render_template的参数来解决。我认为问题出在views.py中,但是如果我缺少代码或其他任何信息,请告诉我。谢谢

views.py

$ionicPlatform.ready(function(){
    $scope.canUseFingerprint = false; //Initialized to false

var ss = new cordova.plugins.SecureStorage(
  function () { 
    console.log('Success');
    // $scope.allowFingerprintLogin = true;
    setTimeout(function(){
      checkForLoginCreds(); //Checks for login credentials
    },3000)

  },
  function (error) { 
    $scope.canUseFingerprint = false;
    addLockScreen();
    console.log('Error ' + error); 

  },
  'my_app');
var checkForLoginCreds = function(){

  ss.get(
    function (value) { 
      console.log('Success, got ' + value); 
      // This should activate the button, but does nothing. It DOES get set to true. Only after typing single character in input does the button show.
      $scope.canUseFingerprint = true; 
    },
    function (error) { console.log('Error ' + error); },
    'loginInfo');
}
})

javascript

@blueprint.route("register/")
def register_page():
    """Renders register site landing page."""
    form = RegisterForm()
    return render_template('main/register.html', page_title="Register", form=form, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])


@blueprint.route("register/", methods=['GET', 'POST'])
def register():
    """Renders register page."""
    form = RegisterForm()
    if request.method == 'POST':
        if not form.validate_on_submit():
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=False)
        # If company does not exist, create it
        if err:
            company, err = create_company(form.organization.data)
            if err:
                return render_template('main/register.html', page_title="Service Registration",
                                       form=form, form_success=False, message=err)
        if err:
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=False, message=err)
        if err:
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=False, message=err)
        else:
            success_msg = "Your ticket id is {}. You should receive an email with a link to your ticket."
                .format(ticket.get('id'))
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=True, message=success_msg)
    return render_template('main/register.html', page_title="Service Registration",
                           form=form)

回溯

var validateContentType = function() {
            var contentType = $('#upload').prop('files')[0].type;

            console.log(contentType, contentType2, contentType3, contentType4, contentType5, contentType6, contentType7);
            var contentTypes = contentType.split('/');

            var MIMEType = contentTypes[0];

            var mediaType = contentTypes[1];

            switch(MIMEType) {
                case 'video':
                    return true;
                case 'image':
                    return true;
                case 'application':
                    if ({{ media_types|tojson }}.indexOf(mediaType) != -1) {
                        return true;
                    } else {
                        return false;
                    }
                default:
                    return false;
            }
        };

1 个答案:

答案 0 :(得分:0)

您没有在media_types路由中将render_template()传递给您的任何register呼叫。对于您提供的特定回溯,罪魁祸首在这里:

return render_template('main/register.html', page_title="Service Registration",
                       form=form, form_success=False)

,但是他也适用于其他render_template()个呼叫。您可以在回溯中看到这一点:

Traceback (most recent call last):
  # [...]
  # line pointing to the register() function, where the above render_template()
  # call is made
  File "C:\Users\snguyen\Documents\Nevco_Support\nevco-support\nevco_support\main\views.py", line 151, in register
    form=form, form_success=False)
  # [...]
  # which leads to this template line, where media_types|tojson is output
  File "C:\Users\snguyen\Documents\Nevco_Support\nevco-support\nevco_support\templates\main\register.html", line 848, in block "js"
    if ({{ media_types|tojson }}.indexOf(mediaType) != -1) {
  # The next line is tojson filter being called
  File "C:\Users\snguyen\Documents\Nevco_Support\venv\lib\site-packages\flask\json.py", line 269, in tojson_filter
    return Markup(htmlsafe_dumps(obj, **kwargs))
  # [...]
  # and the exception tells us something is not serializable, the Undefined object.
TypeError: Object of type 'Undefined' is not JSON serializable

Jinja2将Undefined用于尚未为模板设置的任何变量。来自template documentation

  

如果变量或属性不存在,则将返回未定义的值。可以使用哪种值取决于应用程序配置:默认行为是,如果打印或迭代结束,则求值为空字符串,而其他所有操作均失败。

您需要将media_types的值传递给所有调用,或者将set a default传递给该值(如空字符串):

if ({{ media_types|default("")|tojson }}.indexOf(mediaType) != -1) {