Django商品编辑页面404错误及参数缺失问题求助
Hey there! Let's break down the issues you're facing with your Django product update feature—those 404s and missing parameter errors are super common when starting out, so we'll fix this step by step.
1. The Core Issue: Missing id Parameter in Your URL Pattern
Your Edit_Product view explicitly requires an id parameter to fetch the product instance, but your URL pattern doesn't capture this value. That's why you're getting "missing positional argument" errors and 404s—Django can't match a URL without the id to your view.
Fix your urls.py by adding the <int:id> parameter to the Edit_Product path:
urlpatterns = [ # ... your other paths ... path('shop/product/Edit_Product/<int:id>/', views.Edit_Product, name='Edit_Product'), ]
Now when you access the edit page (e.g., /shop/product/Edit_Product/1/), Django will pass the id value to your view correctly.
2. Incorrect Redirect in Your View
Your current redirect uses a template file path ('shop/product/detail.html'), which isn't how Django's redirect() function works—it expects a URL name or a full URL. This would cause an additional error after saving the product.
Update the redirect in your views.py to use the product's absolute URL (thanks to your get_absolute_url() method):
# Replace this line: # return redirect('shop/product/detail.html') # With this: return redirect(product.get_absolute_url())
Or alternatively, use the URL name directly:
return redirect('shop:product_detail', args=[product.id, product.slug])
3. Optional (But Important) Fix: Slug Field in Edit Form
Your EditProduct form doesn't include the slug field, but your model uses it for URLs and indexing. Right now, if you edit a product's name, the slug won't update automatically (since prepopulated_fields only works if the field is present in the form).
Update your forms.py to include the slug field:
class EditProduct(forms.ModelForm): class Meta: model = Product fields = ["category", "name", "slug", "image", "description", "price", "available"] prepopulated_fields = {'slug': ('name',)}
This lets the slug auto-populate when the name changes, and gives you control to edit it manually if needed.
4. Double-Check Your Edit Link in Templates
Make sure wherever you're linking to the edit page (e.g., in product detail or list views), you're passing the product's id as an argument:
<a href="{% url 'shop:Edit_Product' product.id %}">Edit This Product</a>
This ensures the generated URL includes the required id parameter.
If you apply these changes, your 404 errors and missing parameter issues should disappear. Let me know if you hit any other snags!
内容的提问来源于stack exchange,提问作者Malik Shahrah

