Search code examples
pythondjangodjango-modelsdjango-viewsdjango-templates

Django View: `DoesNotExist` error when trying to edit a product


I'm trying to create an edit product feature in my Django application, but I'm running into a DoesNotExist error when I try to access the edit product page.

Here's my view function:

@login_required
def edit_product(request, pid):
    product = Product.objects.get(pid=pid)
    if request.method == "POST":
        form = AddProductForm(request.POST, request.FILES, instance=product)
        if form.is_valid():
            new_product = form.save(commit=False)
            new_product.user = request.user  # assuming there is a user field in the Product model
            new_product.save()
            form.save_m2m()  # Save many-to-many relationships
            return redirect("vendorpannel:dashboard")
        else:
            # Print form errors for debugging
            print(form.errors)
    else:
        form = AddProductForm(instance=product)

    context = {
        "form": form,
        "product": product,
    }
    return render(request, "vendorpannel/edit-product.html", context)

When I try to access the edit product page, I get the following error:

DoesNotExist at /vendorpannel/edit_product/11
Product matching query does not exist.

I've checked my database, and the product with the specified pid exists. I'm not sure what's causing this error.

Can anyone help me identify the issue and suggest a solution?

if you need my template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Product</title>
    <!-- Bootstrap CSS -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            padding-top: 50px;
        }
        .container {
            max-width: 600px;
            margin: auto;
        }
        .form-group label {
            font-weight: bold;
        }
        .form-actions {
            text-align: right;
        }
        .form-actions button {
            margin-left: 10px;
        }
    </style>
</head>
<body>

<div class="container">
    <h2 class="mb-4">Edit Product</h2>
    <form method="POST" enctype="multipart/form-data" action="{% url 'vendorpannel:edit_product' product.id %}">
        {% csrf_token %}
        <div class="form-group">
            <label for="id_title">Title</label>
            <input type="text" class="form-control" id="id_title" name="title" value="{{ product.title }}" required>
        </div>
        <div class="form-group">
            <label for="id_description">Description</label>
            <textarea class="form-control" id="id_description" name="description" rows="4" required>{{ product.description }}</textarea>
        </div>
        <div class="form-group">
            <label for="id_price">Price ($)</label>
            <input type="number" class="form-control" id="id_price" name="price" value="{{ product.price }}" step="0.01" required>
        </div>
        <div class="form-group">
            <label for="id_status">Status</label>
            <input type="text" class="form-control" id="id_status" name="status" value="{{ product.status }}" required>
        </div>
        <div class="form-group">
            <label for="id_date">Date</label>
            <input type="date" class="form-control" id="id_date" name="date" value="{{ product.date }}" required>
        </div>
        <div class="form-group">
            <label for="id_image">Product Image</label>
            <input type="file" class="form-control-file" id="id_image" name="image">
            {% if product.image %}
                <img src="{{ product.image.url }}" alt="{{ product.title }}" class="img-thumbnail mt-2" style="max-width: 200px;">
            {% endif %}
        </div>
        <div class="form-actions">
            <a href="{% url 'vendorpannel:vendor_shop' %}" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Save Changes</button>
        </div>
    </form>
</div>

<!-- Bootstrap JS and dependencies -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</body>
</html>

Edit:

urls.py:

from django.urls import path
from vendorpannel import views

app_name = 'vendorpannel'

urlpatterns = [
    path('vendor_pannel1/', views.vendor_pannel1, name='vendor_pannel1'),
    path('vendor_signup/', views.vendor_signup, name='vendor_signup'),
    path('login_view/', views.login_view, name='login_view'),
    path('vendor_shop/', views.vendor_shop, name='vendor_shop'),
    path('vendor_tickets/', views.vendor_tickets, name='vendor_tickets'),
    path('vendor_user/', views.vendor_user, name='vendor_user'),
    path('vendor_settings/', views.vendor_settings, name='vendor_settings'),
    path('add_product/', views.add_product, name='add_product'),
    path('edit_product/<pid>', views.edit_product, name='edit_product'),
]

Additional information:

1.I'm using Django 3.2. 2.My Product model has a primary key field named id. 2.I've tried using get_object_or_404 instead of Product.objects.get(), but I still get the same error.

Thanks in advance for your help!


Solution

  • You used pid in your views but tried to access it in your templates using product.id. One way to fix this is to change pid in product = Product.objects.get(pid=pid) to id. Also I suggest you use get_object_or_404:

    product = get_object_or_404(Product, id=pid)
    

    Then in your urls.py:

    path('edit_product/<int:pid>', views.edit_product, name='edit_product'),
    

    This should resolve your DoesNotExist error.