Home > OS >  Url Pattern giving me a url mismatch error
Url Pattern giving me a url mismatch error

Time:03-21

url(r'^(?P<pk>\d )/remove/$',
        WishlistRemoveView.as_view(), name='wishlist_remove'),


<form action="{% url 'wishlist_remove' pk=item.wishlistitem_set.all.0.pk %}" method="post">
    {% csrf_token %}
    <input type="submit" value="{% trans 'Remove' %}">
</form>

When i click on the remove button I get the following error:-

NoReverseMatch at /product/7/
Reverse for 'wishlist_remove' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['(?P<pk>\\d )/remove/$']

Something is wrong

CodePudding user response:

The reason this does not work is because for the given item, your wishlistitem_set.all() is empty, so there is no WishlistItem to remove.

You can make a check with:

{% with wishlistitems=item.wishlistitem_set.all %}
  {% if wishlistitems %}
    <form action="{% url 'wishlist_remove' pk=wishlistitems.0.pk %}" method="post">
      {% csrf_token %}
      <input type="submit" value="{% trans 'Remove' %}">
    </form>
  {% endif %}
{% endwith %}

It is however a bit "odd" to only work with the first item: why should there be a button for the first item, and not the second for example?


Note: As of , url(…) [Django-doc] is deprecated in favor of re_path(…) [Django-doc] and has been removed in . Furthermore a new syntax for paths has been introduced with path converters: you use path(…) [Django-doc] for that.

  • Related