I have a shoppinglist app. I want that when the user clicks on "add to shopping list" the item is saved to the shopping list.
How can I do that?
in the template I wrote:
<a href="javascript:{document.getElementById('add_item').submit()}" class="btn btn-primary btn-block">Add to
shopping list
</a>
<form action="{% url 'add_to_shopping_list' product.id %}" id="add_item" method="POST">
{% csrf_token %}
<input type="hidden">
</form>
in urls.py I dispaced the urls like this:
urlpatterns = [
path('add_to_shopping_list/<int:pk>', views.add_to_shopping_list, name='add_to_shopping_list'),
]
this calls the view add_to_shopping_list where I want create a ShoppingItem object and to link this to the Product object. The problem is that I don't want to redirect the user anywhere, but just stay on the same page without refreshing. But the view wants me to return an HtmlResponse, or I get this error:
The view shoppinglist.views.add_to_shopping_list didn't return an HttpResponse object. It returned None instead.
Is the idea correct? If yes how can I solve this problem? Thanks
EDIT
here is the view.py, this is just the idea, I could not debug it
from . models import ShoppingItem
from products.models import Product
def add_to_shopping_list(request, pk):
item = Product.objects.get(pk=pk)
shopping_list = request.user.shopping_lists.all()[0]
product = ShoppingItem(name=item.name, list=shopping_list, price=item.price)
product.save()
return ???
The Product object already exists, but I need to create a ShoppingItem object that is associated to that shopping list that belongs to that user.
idbefore the object is created. Hence the URL requiring the ID seems wrong.