Django Form Submission Not Triggering `create_cancel` View

Problem Description:
I am implementing an order cancellation feature in my Django application. The process involves displaying a cancellation form (cancel-order.html) using the cancel_order view and processing the form submission with the create_cancel view to update the product_status of CartOrder and CartOrderItems.

However, the issue is that the create_cancel view is not being triggered when the form is submitted. No success or error messages are displayed, and no updates are made to the database.

Views:
Here are the relevant views:

def cancel_order(request, oid):
    sub_category = SubCategory.objects.all()
    categories = Category.objects.prefetch_related('subcategories').order_by('?')[:4]
    wishlist = wishlist_model.objects.filter(user=request.user) if request.user.is_authenticated else None
    nav_category = Category.objects.filter(special_category=True).prefetch_related('subcategories').order_by('?')[:4]
    order = CartOrder.objects.get(user=request.user, id=oid)
    products = CartOrderItems.objects.filter(order=order)

    # Calculate discounts for each product
    total_old_price = 0
    total_price = 0

    for item in products:
        product = item.product  # Assuming a ForeignKey from CartOrderItems to Product
        qty = item.qty  # Assuming a quantity field in CartOrderItems
        total_old_price += (product.old_price or 0) * qty
        total_price += (product.price or 0) * qty

    # Calculate total discount percentage
    if total_old_price > 0:  # Prevent division by zero
        discount_percentage = ((total_old_price - total_price) / total_old_price) * 100
    else:
        discount_percentage = 0

    context = {
        "order": order,
        "products": products,
        "sub_category": sub_category,
        "categories": categories,
        "wishlist": wishlist,
        "nav_category": nav_category,
        "discount_percentage": round(discount_percentage, 2),  # Round to 2 decimal places
    }

    return render(request, 'core/cancel-order.html', context)


def create_cancel(request, oid):
    if request.method == "POST":
        user = request.user

        # Fetch POST data
        reason = request.POST.get('reason')
        description = request.POST.get('description')

        try:
            # Fetch the CartOrder instance
            order_cancel = get_object_or_404(CartOrder, id=oid, user=user)
            order_cancel.product_status = "cancelled"
            order_cancel.save()

            # Fetch related CartOrderItems instances
            order_items = CartOrderItems.objects.filter(order=order_cancel)
            for item in order_items:
                item.product_status = "cancelled"
                item.save()

            # Log the reason and description (if you want to save this somewhere)
            # Example: save to a cancellation model (optional)
            # CancellationReason.objects.create(order=order_cancel, reason=reason, description=description)

            messages.success(request, "Order successfully cancelled.")

        except Exception as e:
            messages.error(request, f"An error occurred: {e}")

        return redirect("core:dashboard")
    else:
        messages.error(request, "Invalid request method.")
        return redirect("core:dashboard")

Template:
Here is the form in the cancel-order.html template:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="{% static './assets/images/logo/favicon.ico'  %}" type="image/x-icon">
    <title>Cancel Order</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: Arial, sans-serif;
        }

        body {
            background-color: #f8f9fa;
            display: flex;
            justify-content: center;
            align-items: center;
            align-items: flex-start; /* Align items at the top to allow vertical scrolling */
            min-height: 100vh;/* Ensure the body covers the viewport */
            padding: 20px;
        }

        .cancel-order-container {
            display: flex;
            align-items: flex-start;
            gap: 20px;
            background: #ffffff;
            width: 100%;
            max-width: 800px;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .cancel-order-container img {
            max-width: 150px;
            height: auto;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .cancel-order-form {
            flex: 1;
        }

        .cancel-order-form h2 {
            margin-bottom: 20px;
            color: #343a40;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #495057;
            font-weight: bold;
        }

        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            font-size: 16px;
        }

        .form-group textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-actions {
            text-align: right;
        }

        .btn {
            display: inline-block;
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        .btn-cancel {
            background-color: #dc3545;
            color: #ffffff;
        }

        .btn-cancel:hover {
            background-color: #c82333;
        }

        .btn-back {
            background-color: #6c757d;
            color: #ffffff;
            margin-right: 10px;
        }

        .btn-back:hover {
            background-color: #5a6268;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background: #ffffff;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .modal-content p {
            margin-bottom: 20px;
            font-size: 18px;
            color: #343a40;
        }

        .modal-buttons {
            display: flex;
            justify-content: center;
            gap: 10px;
        }

        @media (max-width: 576px) {
            .cancel-order-container {
                flex-direction: column;
                align-items: center;
            }

            .cancel-order-container img {
                max-width: 100%;
                margin-bottom: 20px;
            }

            .cancel-order-form {
                width: 100%;
            }

            .btn {
                width: 100%;
                margin-bottom: 10px;
            }

            .btn-back {
                margin-right: 0;
            }

            .form-actions {
                display: flex;
                flex-direction: column;
            }
        }
    </style>
    <script>
        function showConfirmationModal(event) {
            event.preventDefault();
            const modal = document.getElementById('confirmation-modal');
            modal.style.display = 'flex';
        }

        function hideModal() {
            const modal = document.getElementById('confirmation-modal');
            modal.style.display = 'none';
        }

        function confirmAndSubmit() {
            document.querySelector('.cancel-order-form').submit();
        }
    </script>
</head>
<body>
    <div class="cancel-order-container">
        <img src="{{order.images}}" alt="Product Image">
        <form class="cancel-order-form" action="{% url 'core:create_cancel' oid=order.id %}" enctype="multipart/form-data" onsubmit="showConfirmationModal(event)" method="POST">
            {% csrf_token %}
            <h2>Cancel Your Order</h2>
            <div class="form-group">
                <label for="order-number">Order Number</label>
                <input type="text" id="order-number" name="order-number" value="{{order.oid}}" readonly>
            </div>
            <div class="form-group">
                <label for="product-name">Product Name</label>
                <input type="text" id="product-name" name="product-name" value="{{order.title}}" readonly>
            </div>
            <div class="form-group">
                <label for="product-price">Product Price</label>
                <input type="text" id="product-price" name="product-price" value="{{order.price}}" readonly>
            </div>
            <div class="form-group">
                <label for="product-price">Product Old Price</label>
                <input type="text" id="product-price" name="product-price" value="{{order.old_price}}" readonly>
            </div>
            {% if order.size %}
            <div class="form-group">
                <label for="product-price">Product Size</label>
                <input type="text" id="product-price" name="product-price" value="{{order.size}}" readonly>
            </div>
            {% endif %}
            <!-- <div class="form-group">
                <label for="product-price">Product Color</label>
                <input type="text" id="product-price" name="product-price" value="{{order.color}}" readonly>
            </div> -->
            <div class="form-group">
                <label for="reason">Reason for Cancellation</label>
                <select id="reason" name="reason" required>
                    <option value="">Select a reason</option>
                    <option value="delay">Order Delay</option>
                    <option value="changed_mind">Changed My Mind</option>
                    <option value="found_cheaper">Found a Cheaper Option</option>
                    <option value="other">Other</option>
                </select>
            </div>
            <div class="form-group">
                <label for="comments">Additional Comments</label>
                <textarea id="comments" name="comments" placeholder="Provide additional details (optional)"></textarea>
            </div>
            <div class="form-actions">
                <button type="button" class="btn btn-back" onclick="history.back()">Go Back</button>
                <button type="submit" class="btn btn-cancel">Submit</button>
            </div>
        </form>
    </div>

    <!-- Modal -->
    <div id="confirmation-modal" class="modal">
        <div class="modal-content">
            <p>Are you sure to cancel the order? You are saving {{ discount_percentage }}% on this order.</p>
            <div class="modal-buttons">
                <button class="btn btn-back" onclick="hideModal()">No</button>
                <button class="btn btn-cancel" onclick="confirmAndSubmit()">Yes</button>
            </div>
        </div>
    </div>
</body>
</html>

Models:
Here are the CartOrder and CartOrderItems models:

STATUS_CHOICE = (
    ("processing", "Processing"),
    ("shipped", "Shipped"),
    ("out_for_delivery", "Out for delivery"),
    ("delivered", "Delivered"),
    ("return_accepted", "Return Accepted"),
    ("pick_up", "Pick Up"),
    ("refund_completed", "Refund Completed"),
    ("cancelled", "Cancelled"),
)

class CartOrder(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    oid = ShortUUIDField(length=10, max_length=100, prefix="oid", alphabet="1234567890")
    product_status = models.CharField(max_length=50, choices=STATUS_CHOICE, default="processing")
    # Other fields...

class CartOrderItems(models.Model):
    order = models.ForeignKey(CartOrder, on_delete=models.CASCADE, related_name="items")
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    qty = models.PositiveIntegerField(default=1)
    product_status = models.CharField(max_length=50, choices=STATUS_CHOICE, default="processing")
    # Other fields...

URLs:
Here are the URL patterns:

path("cancel_order/<int:oid>", cancel_order, name="cancel_order"),
path("create_cancel/<int:oid>", create_cancel, name="create_cancel"),

Observed Behavior:

  1. The cancel-order.html form renders correctly with the action URL pointing to the create_cancel view.
  2. When submitting the form, the create_cancel view is not triggered.
  3. No success or error messages are displayed.
  4. No changes are made to the product_status fields in the database.

Expected Behavior:
When the form is submitted, the create_cancel view should be triggered, and it should update the product_status fields for the CartOrder and associated CartOrderItems. Success or error messages should be displayed accordingly.

Questions:

  1. What could be causing the create_cancel view to not trigger upon form submission?
  2. Are there any common issues with form submission or URL resolution in Django that I might be overlooking?
  3. Could this be related to how the oid parameter is being passed in the URL or how the POST request is handled?

2

Ok. I found the problem
I did the mistake in URLs
My views:

def cancel_order(request, oid):
    sub_category = SubCategory.objects.all()
    categories = Category.objects.prefetch_related('subcategories').order_by('?')[:4]
    wishlist = wishlist_model.objects.filter(user=request.user) if request.user.is_authenticated else None
    nav_category = Category.objects.filter(special_category=True).prefetch_related('subcategories').order_by('?')[:4]
    order = CartOrder.objects.get(user=request.user, id=oid)
    products = CartOrderItems.objects.filter(order=order)

    # Calculate discounts for each product
    total_old_price = 0
    total_price = 0

    for item in products:
        product = item.product  # Assuming a ForeignKey from CartOrderItems to Product
        qty = item.qty  # Assuming a quantity field in CartOrderItems
        total_old_price += (product.old_price or 0) * qty
        total_price += (product.price or 0) * qty

    # Calculate total discount percentage
    if total_old_price > 0:  # Prevent division by zero
        discount_percentage = ((total_old_price - total_price) / total_old_price) * 100
    else:
        discount_percentage = 0

    context = {
        "order": order,
        "products": products,
        "sub_category": sub_category,
        "categories": categories,
        "wishlist": wishlist,
        "nav_category": nav_category,
        "discount_percentage": round(discount_percentage, 2),  # Round to 2 decimal places
    }

    return render(request, 'core/cancel-order.html', context)


def create_cancel(request, oid):
    if request.method == "POST":
        user = request.user

        # Fetch POST data
        reason = request.POST.get('reason')
        description = request.POST.get('description')

        try:
            # Fetch the CartOrder instance
            order_cancel = get_object_or_404(CartOrder, id=oid, user=user)
            order_cancel.product_status = "cancelled"
            order_cancel.save()

            # Fetch related CartOrderItems instances
            order_items = CartOrderItems.objects.filter(order=order_cancel)
            for item in order_items:
                item.product_status = "cancelled"
                item.save()

            # Log the reason and description (if you want to save this somewhere)
            # Example: save to a cancellation model (optional)
            # CancellationReason.objects.create(order=order_cancel, reason=reason, description=description)

            messages.success(request, "Order successfully cancelled.")

        except Exception as e:
            messages.error(request, f"An error occurred: {e}")

        return redirect("core:dashboard")
    else:
        messages.error(request, "Invalid request method.")
        return redirect("core:dashboard")

and in urls.py:

path("cancel_order/<int:oid>", cancel_order, name="cancel_order"),
path("create_cancel/<int:oid>", create_cancel, name="create_cancel"),

previously I was triggering same view cancel_order instade of create_cancel

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật