Log is a registered user of the site should have the most basic function, so the development of the first function of our personal blog is the user's login and registration, this is based on Django2.0 to override the user's login registration announcement by Django Auth inside the authentication module, the user model table is rewritten using the previous custom table structure inside UserInfo model table, add additional user information.
The overall development of ideas:
With the development of a Django app, to achieve the following, this article only describes a registered user login section
- User Registration: After registration to the login page
- User Login: Go home side after login
- Home plane: the navigation bar (registration login), which published the contents of the website, billboards around the side
- User profile page: View user registration information, and provide information on the Edit button
- Profile edit page: Go to complete the user information Edit user profile page to view information
- User Password Reset
- The user logs off
The first step is to create a user called APP, and modify setting.py
Suppose we have a name for the BBS project, we can enter the directory in a terminal window cmd cd, and enter the following command to create a named users of the App:
python manage.py startapp users
Then setting.py file is added to the winning users INSTALL_APPS:
INSTALLED_APPS = [ 'reg.apps.RegConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', ]
The second step configuration URL
Individual top-down thinking habit, so accustomed to write your url, then write the function logic inside view
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^register/', views.register), url(r'^login/', views.login), url(r'^media/(?P<path>.*)', serve, {'document_root': settings.MEDIA_ROOT}), ]
The third step is the preparation of view view
We need to register and logi you two views, allowing users to submit data to us via ajax, and processes the data, we used the forms component parts
So need to create myform.py file, create a Myform for register function, the code is as follows
Django from Import Forms from `` django.forms`` Import Widgets from app01 Import Models class the MyForm (forms.Form): username = forms.CharField (= 16 MAX_LENGTH, min_length =. 3, label = 'username', error_messages, = { 'required': 'user name can not be empty', 'min_length': 'a user name can not be less than 3', 'MAX_LENGTH': 'username no more than 16', }, the widget = widgets.TextInput (attrs = { ' class ' : 'Control-form'})) password = forms.CharField (= 16 MAX_LENGTH, min_length =. 3, label = 'password', error_messages, = { 'required': 'password can not be empty', 'min_length': 'Password can not be less than 3 ', ' MAX_LENGTH ':' the password is not more than 16 ', Password can not be less than 3 ', }, the widget = widgets.PasswordInput (attrs = {'class ': 'Control-form'})) re_password = forms.CharField (= 16 MAX_LENGTH, min_length =. 3, label = 'Confirm Password', error_messages, = { 'required': 'Confirm Password can not be empty', 'min_length' : 'confirm password not less than 3', 'MAX_LENGTH': 'confirm password not more than 16', }, the widget = widgets.PasswordInput (attrs = { ' class ': 'Control-form'})) In Email = forms.EmailField (label = 'mail', error_messages, = { 'required': 'E-mail can not be empty', 'invalid': 'E-mail format error' }, the widget = widgets.EmailInput (attrs = { ' class ':' form -Control '})) DEF clean_username (Self): user_obj = models.UserInfo.objects.filter(username='username')if user_obj : username = self.cleaned_data.get('username') self.add_error('username','用户名已存在') return username def clean(self): password = self.cleaned_data.get('password') re_password = self.cleaned_data.get('re_password') if not password == re_password: self.add_error('re_password','两次密码不一致') return self.cleaned_data
The above code length, not only do we check the data format, and we added a clean usage, to verify that the user already exists and whether the same password twice.
We alone can help us create a new myform.py post-maintenance, add, modify fields. validation can clean custom form, very convenient form for authentication (checking username, password check, etc.) do not need to view.py, so will clear the entire logic
from django.shortcuts import render, redirect, reverse, HttpResponse from app01.myform import MyForm from app01 import models from django.http import JsonResponse from django.contrib import auth import random from PIL import ImageFont, Image, ImageDraw from io import BytesIO
def register(request): back_dic = { 'code': 100, 'msg': '' } form_obj = MyForm() if request.method == "POST": form_obj = MyForm(request.POST) if form_obj.is_valid(): data = form_obj.cleaned_data # 去除re_password data.pop('re_password') # 获取用户上传的头像文件 file_obj = request.FILES.get('myfile') print(file_obj) if file_obj: data['avatar'] = file_obj models.UserInfo.objects.create(**data) back_dic['msg'] = '注册成功' back_dic['url'] = '/login/' else: back_dic['code'] = 101 back_dic['msg'] = form_obj.errors return JsonResponse(back_dic) return render(request, 'register.html', locals())
def login(request): back_dic = { 'code': 100, 'msg': '' }if request.POST: username = request.POST.get('username') password = request.POST.get('password')code = request.POST.get('code') # 先验证验证码是否一致if request.session.get('code').upper() == code.upper(0): user_obj = auth.authenticate(username=username, password=password)if user_obj: back_dic['msg'] = 'Login successful ' the else auth.login(user_obj) : Back_dic [ ' code '] = 202 back_dic [ 'MSG'] = 'user name or password error' the else : back_dic [ ' code '] = 201 back_dic [ 'MSG'] = 'codes error' return the render (Request, 'login.html', locals ())
We look at the register function is how it works:
- Mr. assembly into an empty forms, rendering to the registration page
- When the user submits the form by post method, I will verify Myforms which data is valid. If so, all data in the forms component comes cleaned_data, whereas our model table, there are no re_password field, so we need to remove re_password fields, and then stored in the database.
- If the registration is successful, you need to go to the login page, so you need to add a url field back_dic inside,
- If you do not submit the form or not to submit the form by post method, we turn to the registration page
Look at the login function is how it works:
- After the user submits the data to verify whether the same code
request.session.get('code').upper() == code.upper(0
auth.authenticate(username=username, password=password)
So in other places we can get through the user object request.user, so easy to call other users of our properties.
Temlate written inside the html file Step Four
Here is the register code:
<div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h1 class="text-center">注册页面</h1> <hr> <form id="my_form"> {% csrf_token %} {% for form in form_obj %} <div class="form-group"> <label for="{{ form.auto_id }}">{{ form.label }}</label> {{ form }} <span class="errors pull-right" style="color: red"></span> </div> {% endfor %} </form> <div class="form-group"> <label for="id_myfile">头像 <img src="/static/img/default.png" id="id_img" alt="" width="80" height="90" style="margin-left:15px"></label> <input type="file" id="id_myfile" name="myfile" style="display: none"> </div> <button class="btn-success btn pull-right" id="id_submit">确认</button> </div> </div> </div>
This is a register of js code
// processing head . $ ( '# Id_myfile') Change ( function () { // Get File objects the let file_obj = the this .files [0]; // Create a built-in objects the let FileReader = new new the FileReader (); // a transferred to the paper document FileReader.readAsDataURL (file_obj); // the acquired file render fileReader.onload = function () { $ ( '# id_img') attr ( 'the src', fileReader.result). } }) ; // data processing Ajax . $ ( '# id_submit') the Click ( function () { the let formData = new new the formData (); . $ .each ($ ( '# My_Form') serializeArray (), function the console.log ($ ( '# My_Form') serializeArray ()).; (index, obj) { formData.append(obj.name, obj.value) }); // 手动添加文件 formData.append('myfile',$('#id_myfile')[0].files[0]); $.ajax({ url: '', type: 'post', data: formData, processData: false, contentType: false, success: function (data) { if (data.code == 100) { location.href = data.url } else { $.each(data.msg, function (index, obj) { let targetId = '#id_' + index;
// 渲染错信息 $(targetId).next().html(obj[0]).parent().addClass('has-error') }) } } }) }); $('input').focus(function () { $(this).next().html('').parent().removeClass('has-error') });
login HTML code
<div class="container-fluid"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <h2 class="text-center">登录</h2> {% csrf_token %} <div class="form-group"> <label for="id_username">用户名</label> <input type="text" name="username" id="id_username" class="form-control"> </div> <div class="form-group"> <label for="id_password">密码</label> <input type="password" name="password" id="id_password" class="form-control"> </div> <div class="form-group"> <label for="id_code">验证码</label> <div class="row"> <div class="col-md-6"> <input type="text" name="code" id="id_code" class="form-control"> </div> <div class="col-md-6"> <img src="/get_code/" alt="" width="310" height="35" id="id_img"> </div> </div> </div> <button class="btn btn-success" id="id_button">登录</button> <span class="errors" style="color: red" id="id_error"></span> </div> </div> </div>
js code
. $ ( '# id_img') the Click ( function () { // Get the old image src path the let OldPath = $ ( the this ) .attr ( 'src'); // the modified image src attribute $ ( the this ) .attr ( 'the src', OldPath + = '?') }); the transmission data Ajax // $ ( '# id_button') the Click (. function () { $ .ajax ({ URL: '', type: 'POST', Data: { 'username': $ ( '# id_username') Val (),. 'password': $ ( '# id_password') Val (),. 'code': $ ( '# id_code') Val (). , // 'csrfmiddlewaretoken':$('[name="csrfmiddlewaretoken"]').val(), 'csrfmiddlewaretoken':'{{ csrf_token }}', }, success:function (data) { if(data.code == 100){ location.href = data.url }else{ $('#id_error').html(data.msg) } } }) })
to sum up:
This article is written registration and login, extends the Django User model that comes with tables and auth authentication module, forms components.