django+vue实现注册登录的示例代码

2022-01-11,,,,

这篇文章主要介绍了django+vue实现注册登录示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

注册

前台利用vue中的axios进行传值,将获取到的账号密码以form表单的形式发送给后台。
form表单的作用就是采集数据,也就是在前台页面中获取用户输入的值。numberValidateForm:前台定义的表单
$axios使用时需要在main.js中全局注册,.then代表成功后进行的操作,.catch代表失败后进行的操作

 submitForm(formName) { let data = new FormData() data.append('username',this.numberValidateForm.name) data.append('password',this.numberValidateForm.pass) this.$axios.post('/api/register/',data).then((res) => { this.$router.push({ name: "login" })  // 路由跳转 }).catch((res) => { console.log("error submit!!"); return false; }) } 

使用$axios进行跨域验证,首先得设置代理,然后在请求头中加入X-CSRFToken

vue.config.js

代理

 proxy: { "/api":{ target:"http://127.0.0.1:8000/", changeOrigin: true  // 是否代理 } },//设置代理, 

main.js

 import Axios from 'axios' Vue.prototype.$axios = Axios let getCookie = function (cookie) { let reg = /csrftoken=([\w]+)[;]?/g return reg.exec(cookie)[1] } Axios.interceptors.request.use( function(config) { // 在post请求前统一添加X-CSRFToken的header信息 let cookie = document.cookie; if(cookie && config.method == 'post'){ config.headers['X-CSRFToken'] = getCookie(cookie); } return config; }, function(error) { // Do something with request error return Promise.reject(error); } );

登录

 submitForm(formName) { this.$refs[formName].validate(valid => {  //vue前台的验证规则 if (valid) { let data = new FormData() data.append('username',this.numberValidateForm.name) data.append('password',this.numberValidateForm.pass) this.$axios.post('/api/login/',data).then((res) => { if(res.data.code == "ok"){ console.log(12345678) this.$router.push({name:"firstpage"}) } }) } else { console.log("error submit!!"); return false; } }); }, 

view.py

django后台视图函数

 from django.shortcuts import render from django.views import View from django.http import HttpResponse,JsonResponse from django.contrib.auth.models import User  # django封装好的验证功能 from django.contrib import auth class Login(View): def post(self,request): try: user = request.POST.get('username',None) pwd = request.POST.get('password',None) # 验证密码 obj = auth.authenticate(request,username=user,password=pwd) if obj: return JsonResponse({'code':'ok','message':'账号密码验证成功'}) except: return JsonResponse({'code':'no','message':'验证失败'}) class Register(View): def post(self, request): try: username = request.POST.get('username',None) password = request.POST.get('password',None) user = User.objects.create_user(username=username,password=password) user.save() except: return JsonResponse({'code':'no','message':'注册失败'}) return JsonResponse({'code':'ok','message':'注册成功'})

到此这篇关于django+vue实现注册登录的示例代码的文章就介绍到这了,更多相关django+vue注册登录内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

以上就是django+vue实现注册登录的示例代码的详细内容,更多请关注本站其它相关文章!

《django+vue实现注册登录的示例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。