Django-将错误消息传递到模板的AJAX错误

时间:2019-04-20 01:20:02

标签: ajax django-templates django-views

我正在尝试使用“消息”将错误消息发送到模板。我一直在使用文档here,并且还查看了一些SO帖子。看起来最有前途的是here。我相信我正在按照说明进行操作,但是已经进行了半天的查找和修改,并且不知道错误在哪里。该消息未显示在页面上,我在代码中找不到错误。

from django.contrib import messages
def new_article(request):
    save_article = SearchResults.objects.new_article(request.POST)
    r_id = save_article
    result_id = ""
    #the try is working as intended and I'm getting the id like I want
    try:
            if int(r_id):
                    result_id = r_id


    # when the link is already in the database then it goes to
    # except ; that portion is working because I'm getting the print  
    except:
            print("article already exists in database")

            # I think the next lines are the problem. I've rearranged them
            # in multiple ways

            messages.error(request,'This article already exists in database')                
            return redirect (reverse('example:results'))

我做了print("article already exists in database"),它起作用了。所以我知道这使它成为例外。

index.html

<body>
<div id="container">
    <h1 id="heading">Results</h1>
    <button id="create-article">Add Article</button>
    {% if messages %}
        <ul class="messages">
        {% for message in messages %}
            <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
        {% endfor %}
        <ul>
    {% endif %}

我的问题是该消息未出现在页面上。

更新:

我认为问题可能出在:return redirect (reverse('example:results'))而非消息功能上。看来模板没有重新加载,因此没有显示新消息。

我将其更改为:return redirect(request,'example/results.html,它给了我这个错误消息:

raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for '<WSGIRequest: POST '/new_article'>' not found. > '<WSGIRequest: POST '/new_article'>'>  is not a valid view function or pattern name.

“ new_article”是脚本中的一个ajax URL

如果刷新页面,则会显示该消息,并且终端中的错误会消失。如何在终端中没有出现以上错误(出现NoReverseMatch(msg)....)并且没有手动刷新页面的情况下,如何用messages.error重新加载页面?

脚本

      $( function() {
    var dialog, form,
    datepicker = $( "#datepicker" ),
    exerciseName = $( "#exampleName" ),
    articleTitle = $( "#articleTitle" ),
    articleLink = $( "#articleLink" ),
    nds_check = $( "#check" ),
    general_notes = $('#Notes'),
    allFields = $( [] ).add( datepicker ).add( exampleName ).add( articleTitle ).add( articleLink ).add( check )
    .add( Notes )
    tips = $( ".validateTips" );

    function updateTips( t ) {
        tips
            .text( t )
            .addClass( "ui-state-highlight" );
        setTimeout(function() {
            tips.removeClass( "ui-state-highlight", 1500 );
        }, 500 );
    }

    function checkLength( o, n, min, max ) {
        if ( o.val().length > max || o.val().length < min ) {
        o.addClass( "ui-state-error" );
        updateTips( "Fields cannot be empty or be longer than 255 characters");
        return false;
        } else {
        return true;
        }
    }


    function addArticle() {
    var valid = true;
    allFields.removeClass( "ui-state-error" );

    valid = valid && checkLength( datepicker, "datepicker", 1, 250 );
    valid = valid && checkLength( exampleName, "exampleName", 1, 100 );
    valid = valid && checkLength( articleTitle, "articleTitle", 1, 250 );
    valid = valid && checkLength( articleLink, "articleLink", 1, 250 );

    if ( valid ) {
        $.ajax({
            url: 'new_article',
            type: 'POST',
            data: $('#new_form').serialize()
                                        })                  
        dialog.dialog( "close" );
    }
    return valid;
    }

    dialog = $( "#dialog-form" ).dialog({
    autoOpen: false,
    height: 900,
    width: 1000,
    modal: true,
    buttons: {
        "Add Article": addArticle,
        Cancel: function() {
        dialog.dialog( "close" );
        }
    },
    close: function() {
        form[ 0 ].reset();
        allFields.removeClass( "ui-state-error" );
    }
    });

    form = dialog.find( "form" ).on( "submit", function( event ) {
    event.preventDefault();
    addArticle();
    });

    $( "#create-article" ).button().on( "click", function() {

        dialog.dialog( "open" );
    });
    } );

    $( function() {
        $( "#datepicker" ).datepicker();
      } );

    $("#nds_check").on('change', function() {
    if ($(this).is(':checked')) {
        $(this).attr('value', 'true');
    } else {
        $(this).attr('value', 'false');
        }
    });  
</script>

我想发生的事情是获取new_article信息,检查数据库。如果链接已经存在,我只想向模板发送一条消息,说明该链接已经存在。

0 个答案:

没有答案