django+vue项目-制作一个简单的购物网站
为了创建一个简单的购物网站,我们可以使用Django作为后端框架和Vue作为前端框架。以下是一个简化的项目结构和基本的代码示例。
后端(Django):
- 安装Django:
pip install django
- 创建新的Django项目和应用:
django-admin startproject shop_backend
cd shop_backend
python manage.py startapp products
- 在
products/models.py
中定义商品模型:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
- 在
products/serializers.py
中创建序列化器:
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'
- 在
products/views.py
中创建视图:
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
- 在
shop_backend/urls.py
中配置路由:
from django.urls import include, path
from rest_framework import routers
from products.views import ProductViewSet
router = routers.DefaultRouter()
router.register(r'products', ProductViewSet)
urlpatterns = [
path('', include(router.urls)),
]
前端(Vue):
- 安装Vue CLI:
npm install -g @vue/cli
- 创建新的Vue项目:
vue create shop_frontend
cd shop_frontend
- 添加Vue Router和Axios:
vue add router
npm install axios
- 在
src/components/ProductList.vue
中创建组件来显示商品列表:
<template>
<div>
<ul>
<li v-for="product in products" :key="product.id">
{{ product.name }} - {{ product.price }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
products: []
};
},
created() {
this.fetchProducts();
},
methods: {
async fetchProducts() {
try {
const response = await axios.get('http://localhost:8000/products/');
this.products = response.data;
} catch (error) {
console.error(error);
}
}
}
};
</script>
- 在
src/router/index.js
中配置路由:
import Vue from 'vue';
import VueRouter from 'vue-router';
impor
评论已关闭