[Answered ]-How to create django model by pressing button

1👍

Here’s a basic example of how you’d set up something like that.
I used a <a> / Link in the template block, but you’ve just got to goto the URL that url template tag generates.

Urls.py

urlpatterns = [
    path('add_to_favorites/<int:product_id>', views.add_to_favorites, name='add_to_favorites'),
]

View.py (super basic)

def add_to_favorites(request, product_id):
    # Current user can *always* be grabbed in the view with `request.user` 
    #   Note: May run into issues if the user is not logged in

    Favorite.objects.get_or_create(product_id=product_id, user=request.user)

    # maybe do a redirect, or render different page

Template Button

<a class="nav-link" href="{% url 'add_to_favorites' product_id=product.pk %}">Add to Favorite</a>

<!--
    This is the URL you need: 

    {% url 'add_to_favorites' product_id=product.pk %}

    'product' being the Var you threw the Product Object in to render the Details
--->

If you want it seamless, it might be a good idea to look into Javascript/Jquery & AJAX, and just POST to that URL

Leave a comment