I'm trying to send an error message to the template using "messages". I've been using the documentation here and I also looked at a few SO posts. The one that looked the most promising is here. I believe that I'm following the instructions, but have been looking and modifying this for half a day and do not know where the mistake is. The message is not being displayed on the page and I can't find the error in my code.

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

I did the print("article already exists in database") and it works. So I know it makes it to the except.

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 %}

The problem I have is that the message does not appear on the page.

UPDATE:

I think the issues might be with: return redirect (reverse('example:results')) and not the messages feature. It appears the template is not reloading and therefore not displaying the new message.

I changed it to: return redirect(request,'example/results.html and it gives me this error message:

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' is an ajax url inside the script

If I refresh the page the message appears and the error in the terminal goes away. How can I reload the page with the messages.error without having the above error(raise NoReverseMatch(msg)....) show up in the terminal and without manually refreshing the page?

script

      $( 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>

What I want to happen is to get the new_article information, check the db. If the link already exists I just want to send a message to the template saying the link already exists.

0 Answers