我正在使用 Vue 和 Django 來做這個項目,但是當我運行我的程式碼時,我不斷收到此錯誤
"Failed to load resource: the server responded with a status of 500 (Internal Server Error) 127.0.0.1:8000/api/v1/products/winter/yellow-jacket-with-no-zipper:1"
我不斷重新加載並等待了 30 分鐘這個錯誤才消失,但它不斷出現。 我不知道我的javascript是否有問題,因為我運行vue專案時沒有任何錯誤。
這是我認為有問題的程式碼。
後端:
產品包中的urls.py模組:
from django.urls import path, include from product import views urlpatterns = [ path('latest-products/', views.LatestProductsList.as_view()), path('products/<slug:category_slug>/<slug:product_slug>', views.ProductDetail.as_view()), ]
前端:
Product.vue腳本:
<template> <div class="page-product"> <div class="columns is-multiline"> <div class="column is-9"> <figure class="image mb-6"> <img v-bind:src="product.get_image"> </figure> <h1 class="title">{{ product.name }}</h1> <p>{{ product.description }}</p> </div> <div class="column is-3"> <h2 class="subtitle">Information</h2> <p>Price: <strong>{{ product.price }}</strong></p> <div class="field has-addons mt-6"> <div class="control"> <input type="number" class="input" min="1" v-model="quantity"> </div> <div class="control"> <a class="button is-dark">Add to Carts</a> </div> </div> </div> </div> </div> </template> <script> import axios from 'axios' export default { name: 'Product', data() { return { product: {}, quantity: 1 } }, mounted() { this.getProduct() }, methods: { getProduct() { const category_slug = this.$route.params.category_slug const product_slug = this.$route.params.product_slug axios .get(`/api/v1/products/${category_slug}/${product_slug}`) .then(response => { this.product = response.data }) .catch(error => { console.log("error") }) } } } </script>
編輯:
經過一番修改,我認為問題是由產品包中的views.py模組引起的
from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from .models import Product from .serializers import ProductSerializer class LatestProductsList(APIView): def get(self, request, format=None): products = Product.objects.all()[0:4] serializer = ProductSerializer(products, many=True) return Response(serializer.data) #I think its this line of code class ProductDetail(APIView): def get_object(self, category_slug, product_slug): try: return Product.objects.filter(category_slug=category_slug).get(slug=product_slug) except Product.DoesNotExist: raise Http404 def get(self, request, category_slug, product_slug, format=None): product = self.get_object(category_slug, product_slug) serializer = ProductSerializer(product) return Response(serializer.data)
修改程式碼後,我發現我是對的。問題出在產品包中的views.py模組。可以在 ProductDetail 類別中的 get_object 函數中看到。
原文:
問題是我在定義類別slug時需要再增加一個底線/底線(這個東西:_),所以
變成了
新版本: