Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a POST method to an a tag in Django

I am trying to write a POST method an "a" tag href but it is not working

I was successful writing it in another page to select from an option but I am trying to implement it in an a href but it is not working

<form method="POST" action="{{ item.get_add_to_cart_url }}">
{% csrf_token %}
<a href="{% url 'core:add-to-cart' order_item.item.slug %}"><i class="fas fa-plus ml-2"></a></i>
</form>

This is the HTML that I am trying to implement the same logic for which is working perfectly

                            {% csrf_token %}
                            <input class="btn btn-primary btn-md my-2 p" type="submit" value="Add to cart">

                            {% if object.variation_set.all %}

                            {% if object.variation_set.sizes %}
                        <select class="form-control" name="size">
                            {% for items in object.variation_set.sizes %}
                            <option value="{{ items.title|lower }}">{{ items.title|capfirst }}</option>
                            {% endfor %}                      
                        </select>
                        {% endif %}
                        {% endif %}

This is the views:


@login_required
def add_to_cart(request, slug):
    item = get_object_or_404(Item, slug=slug)
    order_item_qs = OrderItem.objects.filter(
        item=item,
        user=request.user,
        ordered=False
    )
    print(item)
    print(order_item_qs)
    item_var = []  # item variation
    if request.method == 'POST':
        for items in request.POST:
            key = items
            val = request.POST[key]
            try:
                v = Variation.objects.get(
                    item=item,
                    category__iexact=key,
                    title__iexact=val
                )
                item_var.append(v)
            except:
                pass

        if len(item_var) > 0:
            for items in item_var:
                order_item_qs = order_item_qs.filter(
                    variation__exact=items,
                )

    if order_item_qs.exists():
        order_item = order_item_qs.first()
        order_item.quantity += 1
        order_item.save()
    else:
        order_item = OrderItem.objects.create(
            item=item,
            user=request.user,
            ordered=False
        )
        order_item.variation.add(*item_var)
        order_item.save()

    order_qs = Order.objects.filter(user=request.user, ordered=False)
    if order_qs.exists():
        order = order_qs[0]
        # check if the order item is in the order
        if not order.items.filter(item__id=order_item.id).exists():
            order.items.add(order_item)
            messages.info(request, "This item quantity was updated.")
            return redirect("core:order-summary")
    else:
        ordered_date = timezone.now()
        order = Order.objects.create(
            user=request.user, ordered_date=ordered_date)
        order.items.add(order_item)
        messages.info(request, "This item was added to cart.")
        return redirect("core:order-summary")

Is this the best way to use a Post method?

like image 486
A_K Avatar asked Jun 09 '20 01:06

A_K


People also ask

How do you receive data from a Django form with a post request?

Using Form in a View In Django, the request object passed as parameter to your view has an attribute called "method" where the type of the request is set, and all data passed via POST can be accessed via the request. POST dictionary. The view will display the result of the login form posted through the loggedin.

What is POST method in Django?

Django's login form is returned using the POST method, in which the browser bundles up the form data, encodes it for transmission, sends it to the server, and then receives back its response. GET , by contrast, bundles the submitted data into a string, and uses this to compose a URL.

What is form AS_P in Django?

as_p simply wraps all the elements in HTML <p> tags. The advantage is not having to write a loop in the template to explicitly add HTML to surround each title and field. There is also form. as_table and form. as_ul to also help set the form within the HTML context you wish.


Video Answer


1 Answers

Your form is not submitting anything, it's just an anchor with an href. Notice how the working code has an input of type submit.

There are many ways you can solve it, I propose two:

  1. Add an input or button of type submit.

<input class="btn btn-primary btn-md my-2 p" type="submit" value="Add to cart">
  1. Set a name attribute on the form, and call document.name.submit() when the link is clicked.

<form name="myForm">
...
<a onClick="document.myForm.submit()">...</a>
</form>

You can learn more about the a and form elements here and here

like image 191
WorkShoft Avatar answered Oct 21 '22 04:10

WorkShoft