前后分离Vue3+Django 之简单的登入
- 前端Vue3
<template>
<div>
<el-form :model="form" label-width="100px">
<el-form-item label="用户名">
<el-input v-model="form.username" placeholder="请输入用户名"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleSubmit">登录</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script setup>
import { ref } from 'vue';
import axios from 'axios';
const form = ref({
username: '',
password: ''
});
const handleSubmit = () => {
axios.post('http://127.0.0.1:8000/user/login/', form.value)
.then(response => {
if (response.data.status === 'success') {
alert('登录成功');
// 登录成功后的逻辑,例如跳转到主页
} else {
alert(response.data.message);
}
})
.catch(error => {
console.error('登录失败', error);
alert('登录失败,请检查用户名和密码');
});
};
</script>
效果:
- 后端Django
models.py
用于mysql
# Create your models here.
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(models.Model):
# 添加自定义字段
name = models.CharField(max_length=100, verbose_name="姓名")
password = models.CharField(max_length=100, verbose_name="密码")
views.py
处理
from django.contrib.auth import authenticate
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from .models import CustomUser
@csrf_exempt
@require_http_methods(["POST"])
def user_login(request):
import json
data = json.loads(request.body)
print(data)
username = data.get('username')
password = data.get('password')
password_mysql = CustomUser.objects.get(name=username)
if password_mysql is not None:
if password_mysql.password==password:
return JsonResponse({'status': 'success', 'message': '登录成功'})
else:
return JsonResponse({'status': 'error', 'message': '用户名或密码错误'})
else:
return JsonResponse({'status': 'error', 'message': '用户名不存在'})
应用的urls.py
路由
from django.urls import path
from . import views
urlpatterns = [
path('login/', views.user_login, name='login'),
]
项目的urls
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('user/', include('myapp.urls')),
]
前后端分别启动,就可以进行尝试。
mysql数据里:
问题点:
如果发现前端输入信息后,后端报"OPTIONS /user/login/ HTTP/1.1" 405 0错误。
可以从2个方面去排查,①路由的路径配置 ②Setting中跨域的配置
原文地址:https://blog.csdn.net/fmdpenny/article/details/145322366
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!