快速搭建Python(Django)+Vue环境并实现页面登录注册功能
以下是一个简化的示例,展示如何快速搭建一个使用Django后端和Vue.js前端的登录和注册页面。
后端环境搭建(Django):
创建一个虚拟环境:
python -m venv myenv source myenv/bin/activate
安装Django:
pip install django
创建一个新的Django项目和应用:
django-admin startproject myproject cd myproject django-admin startapp myapp
配置
settings.py
以包含新应用和CORS:INSTALLED_APPS = [ ... 'myapp', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True
创建用户模型和序列化:
# myapp/models.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'email', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) return user # myapp/views.py from rest_framework import generics, permissions from .models import User from .serializers import UserSerializer class UserListCreate(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny]
前端环境搭建(Vue.js):
- 安装Node.js和npm。
创建一个新的Vue.js项目:
npm install -g @vue/cli vue create my-vue-app cd my-vue-app
添加Vue Router和Axios:
npm install vue-router axios --save
创建Vue组件和路由:
// src/router.js import Vue from 'vue' import Router from 'vue-router' import Login from './components/Login.vue' import Registe
评论已关闭