Django+vue registration and login sample code

Django+vue registration and login sample code

register

The front-end uses axios in vue to pass values ​​and sends the obtained account and password to the back-end in the form of a form.
The function of the form is to collect data, that is, to obtain the value entered by the user on the front-end page. numberValidateForm: the form defined in the front-end
$axios needs to be globally registered in main.js when used. .then represents the operation after success, and .catch represents the operation after failure.

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" }) // route jump }).catch((res) => {
         console.log("error submit!!");
         return false;
      })
  }

To use $axios for cross-domain authentication, you must first set up a proxy and then add X-CSRFToken to the request header.

vue.config.js

acting

proxy: {
        "/api":{
          target:"http://127.0.0.1:8000/",
          changeOrigin: true // Whether to use proxy}
    }, //Set proxy,

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) {
    //Add X-CSRFToken header information uniformly before post request 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);
  }
);

Log in

submitForm(formName) {
      this.$refs[formName].validate(valid => { //vue front-end validation rules 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 background view function

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.models import User # Django's encapsulated authentication function 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)
            # Verify password obj = auth.authenticate(request,username=user,password=pwd)
            if obj:
                return JsonResponse({'code':'ok','message':'Account and password verification successful'})
        except:
            return JsonResponse({'code':'no','message':'Verification failed'})

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':'Registration failed'})
        return JsonResponse({'code':'ok','message':'Registration successful'})

This is the end of this article about the sample code for implementing registration and login with Django + Vue. For more relevant Django + Vue registration and login content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Django registration to send verification code by email
  • General Django registration function module implementation method
  • How to register database table in Django admin background
  • Django user login and registration system implementation example
  • Example of user registration, login, and logout functions implemented by Django framework
  • Django implements user registration example explanation
  • Django implements login, registration and logout functions under the auth module
  • Detailed explanation of the process of implementing simple registration function in Python Django
  • Sample code for Django's login and registration system
  • Django completes email user registration and account activation through ajax
  • Implementation of Django Mall Project Registration Function

<<:  Linux system prohibits remote login command of root account

>>:  Detailed explanation of the use of find_in_set() function in MySQL

Recommend

Detailed example of MySQL subquery

Subquery Classification Classification by returne...

Detailed explanation on how to get the IP address of a docker container

1. After entering the container cat /etc/hosts It...

Analysis of Facebook's Information Architecture

<br />Original: http://uicom.net/blog/?p=762...

Detailed explanation of how to detect and prevent JavaScript infinite loops

Table of contents Preface Fix infinite loop in fo...

Design a simple HTML login interface using CSS style

login.html part: <!DOCTYPE html> <html l...

Introduction to nesting rules of html tags

There are many XHTML tags: div, ul, li, dl, dt, d...

How to set default value for datetime type in MySQL

I encountered a problem when modifying the defaul...

Tips for organizing strings in Linux

In Linux operations, we often replace and count s...

Jenkins packaging microservices to build Docker images and run them

Table of contents Environment Preparation start 1...

JavaScript Dom Object Operations

Table of contents 1. Core 1. Get the Dom node 2. ...

MySQL quickly inserts 100 million test data

Table of contents 1. Create a table 1.1 Create te...

mysql 8.0.19 win10 quick installation tutorial

This tutorial shares the installation tutorial of...