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 django-3.1,
url(…)
[Django-doc] is deprecated in favor ofre_path(…)
[Django-doc] and has been removed in django-4.0. Furthermore a new syntax for paths has been introduced with path converters: you usepath(…)
[Django-doc] for that.