[Answered ]-Django Error: Reverse for 'like_post' with arguments '('',)' not found

1πŸ‘

βœ…

At the point you generate the JavaScript code, item is not defined, hence the error. It might be better to encode the URL in the button, and then make an AJAX call to that URL:

<script>
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    const csrftoken = getCookie('csrftoken');

    $(document).on('submit','#like_form',function(e){
        e.preventDefault();
        $.ajax({
            type:'POST',
            url: $(this).attr("url"),
            data : {csrfmiddlewaretoken: csrftoken},
            success:function(){
            }
        });
    });
</script>

{% block content %}

{% for item in products %}

<div class="item_btns_container">
    <div class="like_btn_form_container">
        <form id="like_form">
            {% csrf_token %}
            {% if user in item.likes.all %}
                <button type="submit" class="liked_post" url="{% url 'like_post' item.id %}" name="post_id" value="{{ item.id }}"><div class="liked_btn" >Like</div></button>
            {% else %}
                <button type="submit" class="like_btn" url="{% url 'like_post' item.id %}" name="post_id" value="{{ item.id }}"><div class="liked_btn">Like</div></button>
            {% endif %}
        </form>
    </div>
{% endfor %}

{% endblock content %}

Leave a comment